rbinding a list of data frame R with NULL

走远了吗. 提交于 2021-02-08 05:44:49

问题


I have a list of data frame structure like this:

Lets call this list listA:

$ :'data.frame':      1 obs. of 3 variables:
 ..$ a             :chr a1
 ..$ b             :chr b1
 ..$ c             :chr c1

$ : NULL

$ :'data.frame':      1 obs. of 3 variables:
 ..$ a             :chr a3
 ..$ b             :chr b3
 ..$ c             :chr c3

How do I preserves the order of the data, keeping the record NULL with either NA and form a data frame like this?

     a    b    c
1:  a1    b1   c1
2:  NA    NA   NA
3:  a3    b3   c3

I have tried to use:

listA <- data.frame(do.call(rbind, listA))

but the end result will skip the second row, becoming like this:

     a    b    c
1:  a1    b1   c1
2:  a3    b3   c3

回答1:


We can create a condition to get NA if it is NULL and then do the rbindlist

rbindlist(lapply(listA, function(x) if(is.null(x)) data.frame(a = NA, b = NA, c= NA) else x))
#    a  b  c
#1: a1 b1 c1
#2: NA NA NA
#3: a3 b3 c3

Another option may be to assign the NULL based on the lengths (which return 0 for NULL elements) to assign 'data.frame' with NA elements and then do the rbindlist

listA[!lengths(listA)] <-  list(data.frame(a = NA, b = NA, c = NA))
rbindlist(listA)


来源:https://stackoverflow.com/questions/48793099/rbinding-a-list-of-data-frame-r-with-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!