watchtower watchtower - 4 years ago 126
R Question

Preserving missing fields when row-wise binding elements of a list in R

I have a named list, and I want to bind its elements. I am a big fan of

data.table::rbindlist()
but it removes NA entries. Is there anyway I can preserve NA entries?

Here's my code:

dput(Result)
structure(list(a = c(1L, 3L), b = c(2L, 4L), c = 4L, d = integer(0),
e = integer(0), f = integer(0)), .Names = c("a", "b", "c",
"d", "e", "f"))


Here's what I tried for
data.table


Attempt1 : Using
data.table


Result1<-data.table::rbindlist(lapply(Result, as.data.frame),use.names=TRUE, fill=TRUE, idcol="Name")


However, I lost
d
and
e
.

Attempt2 : Using
dplyr


dplyr::bind_rows(lapply(Result, as.data.frame))

Again, I lost
d
and
e
.

Expected Output:

Result1
Name X[[i]]
1: a 1
2: a 3
3: b 2
4: b 4
5: c 4
6: d NA
7: e NA
8: f NA


I'd appreciate any help.

Answer Source

Here you go:

Result = structure(list(a = c(1L, 3L), b = c(2L, 4L), c = 4L, d = integer(0), 
               e = integer(0), f = integer(0)), .Names = c("a", "b", "c", 
                                                           "d", "e", "f"))

Result2 = lapply(Result, function(x){
    if(length(x)==0){NA}else{x}
    })

Result3 = data.table::rbindlist(lapply(Result2, 
        as.data.frame),use.names=TRUE, fill=TRUE, idcol="Name")

The problem is that integer(0) is not NA, so you must convert them to NA as shown for Result2.

Result:

> Result3
   Name X[[i]]
1:    a      1
2:    a      3
3:    b      2
4:    b      4
5:    c      4
6:    d     NA
7:    e     NA
8:    f     NA
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download