[英]R list get first item of each element
This should probably be very easy for someone to answer but I have had no success on finding the answer anywhere. 对于某人来说,这应该很容易回答,但是我在任何地方都找不到答案。
I am trying to return, from a list in R, the first item of each element of the list. 我试图从R中的列表返回列表中每个元素的第一项。
> a
[1] 1 2 3
> b
[1] 11 22 33
> c
[1] 111 222 333
> d <- list(a = a,b = b,c = c)
> d
$a
[1] 1 2 3
$b
[1] 11 22 33
$c
[1] 111 222 333
Based on the construction of my list d above, I want to return a vector with three values: 基于上面列表d的构造,我想返回一个带有三个值的向量:
return 1 11 111
You can do 你可以做
output <- sapply(d, function(x) x[1])
If you don't need the names 如果你不需要名字
names(output) <- NULL
sapply(d, "[[", 1)
should do the trick. sapply(d, "[[", 1)
应该可以解决问题。
A bit of explanation: 一点解释:
sapply
: iterates over the elements in the list sapply
:遍历列表中的元素
[[
: is the subset function. [[
:是子集函数。 So we are asking sapply to use the subset function on each list element. 因此,我们要求Sapply在每个列表元素上使用子集函数。
1 : is an argument passed to "[[" 1:是传递给“ [[”的参数
It turns out that "[" or "[[" can be called in a traditional manner which may help to illustrate the point: 事实证明,可以以传统方式调用“ [”或“ [[”,这可能有助于说明这一点:
x <- 10:1
"["(x, 3)
# [1] 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.