Combing a list of unequal data.frames

后端 未结 3 1325
灰色年华
灰色年华 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: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
    

提交回复
热议问题