在R

时间:2017-02-06 04:37:33

标签: r data.table dplyr

我有一个命名列表,我想绑定它的元素。我是data.table::rbindlist()的忠实粉丝,但它删除了NA条目。无论如何我可以保留NA条目吗?

这是我的代码:

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"))

这是我为data.table

尝试的内容

尝试1 :使用data.table

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

但是,我丢失了de

尝试2 :使用dplyr

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

同样,我丢失了de

预期输出:

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

我很感激任何帮助。

2 个答案:

答案 0 :(得分:3)

你走了:

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")

问题是integer(0)不是NA,因此您必须将其转换为NA,如Result2所示。

<强>结果:

> 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

答案 1 :(得分:3)

用NA替换零长度元素,然后使用rbindlist

Result[!lengths(Result)] <- NA
## or
## is.na(Result) <- !lengths(Result)
rbindlist(lapply(Result, as.data.table), id = "Name")
#    Name V1
# 1:    a  1
# 2:    a  3
# 3:    b  2
# 4:    b  4
# 5:    c  4
# 6:    d NA
# 7:    e NA
# 8:    f NA

您也可以在基地R中使用

执行此操作
is.na(Result) <- !lengths(Result)
data.frame(
    Name = rep(names(Result), lengths(Result)),
    V1 = unlist(Result, use.names = FALSE)
)
#   Name V1
# 1    a  1
# 2    a  3
# 3    b  2
# 4    b  4
# 5    c  4
# 6    d NA
# 7    e NA
# 8    f NA