【问题标题】:return list with elements from list of lists从列表列表中返回包含元素的列表
【发布时间】:2018-11-02 17:39:58
【问题描述】:

我有一个列表列表,例如“testccffilt”下面的输入示例。我正在尝试返回一个列表,我从每个列表中选择名称和滞后。例如,对于第一个列表,它将是:

c(‘TimeToShip’,1)

我已经尝试了下面的 lapply 示例,但它并没有给出我想要的输出。我在下面也有一个我想要得到的所需输出类型的例子。非常感谢任何提示。

输入:

> testccffilt

$TimeToShip
           cor lag
3284 0.9998749   1

$TimeToRelease
           cor lag
3285 0.9997293   2

试过了:

testlist<-lapply(testccffilt,function(x)list(names(x),x$lag))

测试列表

$TimeToShip
$TimeToShip[[1]]
[1] "cor" "lag"

$TimeToShip[[2]]
[1] 1


$TimeToRelease
$TimeToRelease[[1]]
[1] "cor" "lag"

$TimeToRelease[[2]]
[1] 2

想要的输出:

[[1]]
[1] "TimeToShip" "1"         

[[2]]
[1] "TimeToRelease" "2"     

数据:

dput(testccffilt)
structure(list(TimeToShip = structure(list(cor = 0.999874880882358, 
    lag = 1), .Names = c("cor", "lag"), row.names = 3284L, class = "data.frame"), 
    TimeToRelease = structure(list(cor = 0.999729343078789, lag = 2), .Names = c("cor", 
    "lag"), row.names = 3285L, class = "data.frame")), .Names = c("TimeToShip", 
"TimeToRelease"))

【问题讨论】:

  • @markus 感谢您这么快回复我。我在 dput(testccffilt) 的原始帖子中添加了更新

标签: r list lapply


【解决方案1】:

这是一个使用 for 循环的选项

out <- vector(mode = "list", length(testccffilt))
for (i in 1:length(testccffilt)) {
  out[[i]] <- c(names(testccffilt)[[i]], testccffilt[[i]][["lag"]])
}
out
#[[1]]
#[1] "TimeToShip" "1"         

#[[2]]
#[1] "TimeToRelease" "2" 

另一个选项是lapply,它可能会更快。

lapply(1:length(testccffilt), function(x)
  c(names(testccffilt)[[x]], testccffilt[[x]][["lag"]]))

【讨论】:

  • 为什么不lapply
  • @Masoud 喜欢这样:lapply(1:length(testccffilt), function(x) c(names(testccffilt)[[x]], testccffilt[[x]][["lag"]])) ?
  • 没错,那不是更快吗?
  • @Masoud Dunno。我不觉得它更容易阅读,所以我决定支持 for 循环。正在考虑Map,但无法正常工作。你会考虑加入一个基准吗?
  • @markus 谢谢,效果很好!列表列表让我很头疼。
猜你喜欢
  • 2022-10-14
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多