将单个元素列表(包括NULL)更有效地转换为向量

Gop*_*ala 1 r

所以,我有一个这样的列表,并希望转换为一个向量,其中空列表被NA替换.列表中的所有条目最多只有一个元素(感谢MongoDB,它只返回嵌套元素作为列表).

有没有更有效的方法来做这个而不是循环(申请家庭)?

dput(l)
list(structure(list(), .Names = character(0)), structure(list(
    postcode = "27612"), .Names = "postcode"), structure(list(
    postcode = "30127"), .Names = "postcode"), structure(list(
    postcode = "35173"), .Names = "postcode"), structure(list(
    postcode = "30047"), .Names = "postcode"), structure(list(
    postcode = "87571"), .Names = "postcode"))
sapply(l, function(x) if (length(x)) unlist(x$postcode) else NA)
[1] NA      "27612" "30127" "35173" "30047" "87571"
Run Code Online (Sandbox Code Playgroud)

输出正是我想要的,但是对于非常大的数据集的恐惧,这将是缓慢的.希望有更快的方法.

Aru*_*run 5

我会做:

ll[!lengths(ll)] <- NA
unlist(ll, use.names=FALSE)
Run Code Online (Sandbox Code Playgroud)

[<-没有深层复制整个列表.您可以通过查看操作前后的地址来查看此信息.