如何获取R中列表中的最后一个元素

Roy*_*Roy 5 r list sapply

我想获取列表中的每个最后一个元素。我发现通过使用 sapply 函数,可以获得第一个元素。

sapply(a,`[`,1)
Run Code Online (Sandbox Code Playgroud)

但是,我实际上并没有理解 是什么意思[,以及如何以类似的方式获取最后一个元素。此代码不起作用。

sapply(a,`]`,1)
Run Code Online (Sandbox Code Playgroud)

ugu*_*ros 7

通过使用列表/向量的长度:

a[length(a)]
Run Code Online (Sandbox Code Playgroud)

对于最后“n”个元素:

a[length(a)-n+1]
Run Code Online (Sandbox Code Playgroud)

例子:

a[length(a)-1] #the 2nd last element
a[length(a)-2] #the 3rd last element
a[length(a)-8] #the 9th last element
Run Code Online (Sandbox Code Playgroud)


mat*_*awn 5

我带着同样的问题来到这里,看到答案一定被忽略了,但对我来说,@akrun 像往常一样有对我有用的答案。所以在没有正确答案的情况下,它是:

sapply(a, tail, 1)