简体   繁体   English

R列表获取每个元素的第一项

[英]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.

相关问题 R - 使用列表中每个项目的第一个元素过滤列表 - R - Filter List Using First Element of Each Item in the List 更新R中每个列表元素中的第一个值 - Update first value in each list element in R 从列表的每个元素中获取最长的项目 - Get the longest item from each element of the list 如何索引列表的第一个元素,并将其应用于 R 中的 dataframe 的每一行? - How to index the first element of a list, and apply it to each row of a dataframe in R? R 递归获取任意深度嵌套列表的第一个元素的名称 - R recursively get the name of the first element of a nested list of arbitrary depth r获取向量中每个单词的第一个,前两个,前三个字母的列表 - r get list of first, first two, first three letters of each word in a vector R:如何从列表的每个内部元素中删除第一个元素而不将其转换为矩阵? - R: How do I remove the first element from each inner element of a list without converting it to matrix? 将每个因子的第一个元素转换为R中的NA - Convert first element of each factor to NA in R 将一个列表中的每个项目与r中另一个列表的每个项目合并 - combine each item from one list with each item of another in r 如何在R中的列表的每个向量(长度不同)中附加第一个和最后一个元素,而又不使代码变慢? - How to append first and last element in each vector (of a different length) of a list in R, without making the code slow?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM