list 选择嵌套列表的第一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20428742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select first element of nested list
提问by Alex
Let's say I have a list like this:
假设我有一个这样的列表:
x = list(list(1,2), list(3,4), list(5,6))
I would like a list that contains only the first elements of the nested list. I can do this by returning another list like so
我想要一个只包含嵌套列表的第一个元素的列表。我可以通过像这样返回另一个列表来做到这一点
x1 = lapply(x, function(l) l[[1]])
Is there shortcut notation for this?
这有快捷方式吗?
回答by A5C1D2H2I1M1N2O1R2T1
Not much of a shortcut, but you can do this:
没有多少捷径,但你可以这样做:
lapply(x, `[[`, 1)
# [[1]]
# [1] 1
#
# [[2]]
# [1] 3
#
# [[3]]
# [1] 5
回答by Alex
Another possibility uses the nice purrr
library:
另一种可能性是使用 nicepurrr
库:
library(purrr)
map(x, 1)
回答by Greg Snow
For your example list you can just do:
对于您的示例列表,您可以执行以下操作:
unlist(x)[ c(TRUE,FALSE) ]
but that depends on each sublist having exactly 2 elements.
但这取决于每个子列表恰好有 2 个元素。
If there are different numbers of elements then you could first do an sapply
to calculate the lengths, then compute the corresponding 1st element positions (see cumsum
), then select those values from the unlist
ed list. But by that time the accepted answer is probably much simpler.
如果元素数量不同,那么您可以先sapply
计算长度,然后计算相应的第一个元素位置(请参阅cumsum
),然后从unlist
ed 列表中选择这些值。但到那时,公认的答案可能要简单得多。
If all the sublists have the same length (but could be different from 2) then you could do something like:
如果所有子列表的长度相同(但可能与 2 不同),那么您可以执行以下操作:
do.call( rbind, x)[,1]
or some other cast to a common object. But I doubt that this would be as efficient as the lapply
approach.
或其他一些转换为公共对象。但我怀疑这是否与该lapply
方法一样有效。
回答by Ronak Shah
We can use pluck
from rvest
which selects 1st element from each nested list
我们可以使用pluck
from rvest
which 从每个嵌套列表中选择第一个元素
rvest::pluck(x, 1)
#[[1]]
#[1] 1
#[[2]]
#[1] 3
#[[3]]
#[1] 5
Note that this gives different result with pluck
from purrr
which selects 1st element (x[[1]]
)
请注意,这给出了不同的结果,pluck
从中purrr
选择第一个元素 ( x[[1]]
)
purrr::pluck(x, 1)
#[[1]]
#[1] 1
#[[2]]
#[1] 2