2

I have a huge list of data frame with different number of columns. I want to loop through each list of data frame and merge them despite the different number of columns.

data<-list()
data[[1]]<-data.frame(x=c(1,4),b=c(7,8),d=c(5,4),y=c(4,7),h=c(8,5)
data[[2]]<-data.frame(x=c(1,NA),b=c(7,8),d=c(5,NA),y=c(4,NA),h=c(8,NA),a=c(NA,87),z=c(NA,7))

Here is my trial, but I am not getting the desired output :(

 comined_df<-function(index)
    {
      if (nrow(as.data.frame(data[index]))>0)
        {
            cleaned_data_frame <- dplyr::bind_rows(as.data.frame(data[index]))
        }
      else
        {
            return(NULL)
        }
    }

combined_df_final<-lapply(1:length(data), comined_df)

The desired output is as follows:

  x b  d  y  h  a  z
1  1 7  5  4  8 NA NA
2  4 8  4  7  5 NA NA
3  1 7  5  4 NA NA NA
4 NA 8 NA NA NA NA  7

Can anyone help me achieving this please?

user86907
  • 817
  • 9
  • 21

1 Answers1

4

You can use dplyr::bind_rows or data.table::rbindlist

dplyr::bind_rows(data)

#   x b  d  y  h  a  z
#1  1 7  5  4  8 NA NA
#2  4 8  4  7  5 NA NA
#3  1 7  5  4  8 NA NA
#4 NA 8 NA NA NA 87  7

With data.table :

data.table::rbindlist(data, fill = TRUE)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213