R列表获取每个元素的第一项 [英] R list get first item of each element

查看:1276
本文介绍了R列表获取每个元素的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某人来说,这应该很容易回答,但是我在任何地方都找不到答案.

This should probably be very easy for someone to answer but I have had no success on finding the answer anywhere.

我试图从R中的列表返回列表中每个元素的第一项.

I am trying to return, from a list in R, the first item of each element of the list.

> 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

基于上面我的列表d的构造,我想返回一个带有三个值的向量:

Based on the construction of my list d above, I want to return a vector with three values:

return  1 11 111

推荐答案

sapply(d, "[[", 1)应该可以解决问题.

一些解释:

sapply:遍历列表中的元素
[[:是子集函数.因此,我们要求Sapply在每个列表元素上使用子集函数.
1:是传递给"[["

sapply: iterates over the elements in the list
[[: is the subset function. So we are asking sapply to use the subset function on each list element.
1 : is an argument passed to "[["

事实证明,可以以传统方式调用"["或"[[",这可能有助于说明这一点:

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

这篇关于R列表获取每个元素的第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆