Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you make all dataframes in a list have the same number of columns?

I’m trying to make all dataframes in a list have the same number of columns.

Create a list of 3 dataframes, but the 2nd has 1 extra column.

    my_data<- 
        list(    data.frame(
         V1= c(1,1,1,1,1),
         V2= c(2,2,2,2,2),
         V3= c(3,3,3,3,3),
         V4= c(4,4,4,4,4),
         V5= c(5,5,5,5,5)), 
       data.frame(
         V1= c(1,1,1,1,1),
         V2= c(2,2,2,2,2),
         V3= c(3,3,3,3,3),
         V4= c(4,4,4,4,4),
         V5= c(5,5,5,5,5),
         V6= c(6,6,6,6,6)),
       data.frame(
         V1= c(1,1,1,1,1),
         V2= c(2,2,2,2,2),
         V3= c(3,3,3,3,3),
         V4= c(4,4,4,4,4),
         V5= c(5,5,5,5,5))

manual removal of column: if df[[2]] has > 5 columns, remove the 6th

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if (ncol(my_data[[2]])>5) {
my_data[[2]][,-6]
}

But why doesn’t the same logic doesn’t work when looping it through the list?

for (i in 1:length(my_data)) {

 if (ncol(my_data[[i]])>5) {
my_data[[i]][,-6]
 } 
}

>Solution :

Your logic works just fine. When you are iterating through the loop, you have to assign the updated frame back to that element of the list.

Simply replace:

my_data[[i]][,-6]

with

my_data[[i]]<-my_data[[i]][,-6]

within the if clause.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading