rbinding a list of data frame R with NULL

Gabriel Source

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
rdataframe

Answers

answered 3 days ago akrun #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)

comments powered by Disqus