【发布时间】:2022-11-05 00:01:48
【问题描述】:
我有这两个列表(假设我们有数百个列表):
l1 = list(c(1,2,3),c(12))
l2 = list(data.frame(x=c(1,2,3)),c(4,5))
我希望只从每个列表中选择第二个元素。怎么做?谢谢。
【问题讨论】:
我有这两个列表(假设我们有数百个列表):
l1 = list(c(1,2,3),c(12))
l2 = list(data.frame(x=c(1,2,3)),c(4,5))
我希望只从每个列表中选择第二个元素。怎么做?谢谢。
【问题讨论】:
尝试
f1 <- function(lstobj)
{
lapply(lstobj, (x) if(is.data.frame(x)) x[[1]][2] else x[2])
}
【讨论】:
要选择每个列表的第二个元素,您可以使用 lapply 与 "[[" 和 2,如下所示:
l1 = list(c(1,2,3),c(12))
l2 = list(data.frame(x=c(1,2,3)),c(4,5))
lists <- list(l1, l2)
lapply(lists, "[[", 2)
#> [[1]]
#> [1] 12
#>
#> [[2]]
#> [1] 4 5
创建于 2022-11-04,reprex v2.0.2
【讨论】: