【问题标题】:Turning single element lists, including NULL, to vector more efficiently将单个元素列表(包括 NULL)转换为更有效的向量
【发布时间】:2016-06-17 22:29:32
【问题描述】:

所以,我有一个这样的列表,并且想要转换为一个向量,其中空列表被替换为 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"

输出正是我想要的,但担心在非常大的数据集上,这会很慢。希望有更快的方法。

【问题讨论】:

    标签: r


    【解决方案1】:

    我愿意:

    ll[!lengths(ll)] <- NA
    unlist(ll, use.names=FALSE)
    

    [&lt;- 不会深度复制整个列表。您可以通过查看操作前后的地址来检查这一点。

    【讨论】:

    • 非常好......在我正在处理的情况下,这个邮政编码是另一个列表的命名字段。所以,看起来我将不得不循环以首先从所有元素中提取该字段,然后运行它。也许循环是我能做的最好的。
    • 这比我的建议快很多,主要是因为lengthssapply(l, length)快很多
    • @Gopala,不确定..也许值得问一个问题。也许其他人有办法处理它..
    • 我刚刚发布了一个新问题,其中包含更完整的数据和问题。希望在我遇到性能和类强制挑战时解决它。
    【解决方案2】:

    我认为预先分配一个 NA 向量然后填充数据可能会更快

    x2 <- rep(NA, length(l))
    x2[sapply(l,length) == 1] <- unlist(l)
    

    但是,至少对于这个大小的数据集,它似乎几乎和你的方法一样快。

    library("microbenchmark")
    microbenchmark(
      sapply(l, function(x) if (length(x)) unlist(x$postcode) else NA), 
      {
        x2 <- rep(NA, length(l))
        x2[sapply(l,length) == 1] <- unlist(l)
      }
    )
    Unit: microseconds
                                                                             expr    min     lq     mean median      uq     max neval
       sapply(l, function(x) if (length(x)) unlist(x$postcode) else NA) 22.325 24.012 34.61623 25.056 44.2935 111.639   100
     {x2 <- rep(NA, length(l)) x2[sapply(l, length) == 1] <- unlist(l)} 22.306 24.485 31.44310 25.478 34.5840  90.339   100
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多