获取向量的最后n个元素。有没有比使用length()函数更好的方法? [英] Getting the last n elements of a vector. Is there a better way than using the length() function?
问题描述
如果为了论证的缘故,我想在Python中使用10长度向量的最后五个元素,我可以在范围索引中使用 - 运算符,所以:
If, for argument's sake, I want the last five elements of a 10-length vector in Python, I can use the "-" operator in the range index so:
>>> x = range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[-5:]
[5, 6, 7, 8, 9]
>>>
R中最好的方法是什么?有没有比我目前使用length()函数更简洁的方法?
What is the best way to do this in R? Is there a cleaner way than my current technique which is to use the length() function?
> x <- 0:9
> x
[1] 0 1 2 3 4 5 6 7 8 9
> x[(length(x) - 4):length(x)]
[1] 5 6 7 8 9
>
这个问题与btw的时间序列分析有关,它通常只适用于最近的数据。
The question is related to time series analysis btw where it is often useful to work only on recent data.
推荐答案
参见?tail
和?head
用于一些方便的功能:
see ?tail
and ?head
for some convenient functions:
> x <- 1:10
> tail(x,5)
[1] 6 7 8 9 10
对于参数清酒:除了最后五个要素之外的所有内容都是:
For the argument's sake : everything but the last five elements would be :
> head(x,n=-5)
[1] 1 2 3 4 5
正如@Martin Morgan在评论中所说,还有另外两种可能性比尾部解决方案更快,以防你必须在1亿个值的向量上进行一百万次。为了便于阅读,我会选择尾巴。
As @Martin Morgan says in the comments, there are two other possibilities which are faster than the tail solution, in case you have to carry this out a million times on a vector of 100 million values. For readibility, I'd go with tail.
test elapsed relative
tail(x, 5) 38.70 5.724852
x[length(x) - (4:0)] 6.76 1.000000
x[seq.int(to = length(x), length.out = 5)] 7.53 1.113905
基准代码:
require(rbenchmark)
x <- 1:1e8
do.call(
benchmark,
c(list(
expression(tail(x,5)),
expression(x[seq.int(to=length(x), length.out=5)]),
expression(x[length(x)-(4:0)])
), replications=1e6)
)
这篇关于获取向量的最后n个元素。有没有比使用length()函数更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!