返回列表与列表列表中的元素

问题描述 投票:1回答:1

我有一个列表列表,如“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))

testlist

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

Data:

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"))
r list lapply
1个回答
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"]]))
© www.soinside.com 2019 - 2024. All rights reserved.