Combing a list of unequal data.frames

后端 未结 3 1308
灰色年华
灰色年华 2020-12-22 01:15

I\'m trying to combine a list of unequal data.frames; the obvious do.call(rbind, df.lst) fails but the real problem is padding it out with NAs.

相关标签:
3条回答
  • 2020-12-22 01:17

    Try

    library(plyr)
    ldply(df.lst,data.frame)
    
      .id a b d  e  f  g
    1   A 1 5 2  1  1  1
    2   A 2 4 3  1  2  2
    3   B 1 3 2 NA NA NA
    4   B 2 2 3 NA NA NA
    5   C 1 4 1  1 NA NA
    6   C 2 3 2  3 NA NA
    

    If needed you can remove the first column :

    df<-ldply(df.lst,data.frame)
    df[,-1]
    
    a b d  e  f  g
    1 1 5 2  1  1  1
    2 2 4 3  1  2  2
    3 1 3 2 NA NA NA
    4 2 2 3 NA NA NA
    5 1 4 1  1 NA NA
    6 2 3 2  3 NA NA
    
    0 讨论(0)
  • 2020-12-22 01:28

    If you want to stick with base R, you can do something like this:

    ### Get all the columns names
    col <- unique(unlist(sapply(df.lst, names)))
    col
    ## [1] "a" "b" "d" "e" "f" "g"
    
    ### Fill the missing columns with NA
    df.lst <- lapply(df.lst, function(df) {
      df[, setdiff(col, names(df))] <- NA
      df
    })
    
    ### Then Bind it
    do.call(rbind, df.lst)
    ##     a b d  e  f  g
    ## A.1 1 5 2  1  1  1
    ## A.2 2 4 3  1  2  2
    ## B.1 1 3 2 NA NA NA
    ## B.2 2 2 3 NA NA NA
    ## C.1 1 4 1  1 NA NA
    ## C.2 2 3 2  3 NA NA
    
    0 讨论(0)
  • 2020-12-22 01:37

    We can use

    library(dplyr)
    bind_rows(df.lst)
    

    Or

    library(data.table)
    rbindlist(df.lst, fill=TRUE)
    
    0 讨论(0)
提交回复
热议问题