获取向量的最后 n 个元素.有没有比使用 length() 函数更好的方法? [英] Getting the last n elements of a vector. Is there a better way than using the length() function?
问题描述
如果为了论证,我想要 Python 中 10 长度向量的最后五个元素,我可以在范围索引中使用-"运算符,因此:
<预><代码>>>>x = 范围(10)>>>X[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>x[-5:][5, 6, 7, 8, 9]>>>在 R 中执行此操作的最佳方法是什么?有没有比我目前使用 length() 函数更简洁的方法?
>x <- 0:9>X[1] 0 1 2 3 4 5 6 7 8 9>x[(长度(x) - 4):长度(x)][1] 5 6 7 8 9>
顺便说一下,这个问题与时间序列分析有关,其中仅处理最近的数据通常很有用.
查看 ?tail
和 ?head
一些方便的功能:
>x <- 1:10>尾巴(x,5)[1] 6 7 8 9 10
为了论证:除了最后五个元素之外的所有元素都是:
>头(x,n = -5)[1] 1 2 3 4 5
正如@Martin Morgan 在评论中所说的那样,还有两种比尾部解决方案更快的可能性,以防您必须在 1 亿个值的向量上执行一百万次.为了可读性,我会用尾巴.
测试已用相对尾(x,5)38.70 5.724852x[长度(x) - (4:0)] 6.76 1.000000x[seq.int(to = length(x), length.out = 5)] 7.53 1.113905
基准代码:
require(rbenchmark)x <- 1:1e8打电话(基准,c(列表(表达式(尾(x,5)),表达式(x[seq.int(to=length(x), length.out=5)]),表达式(x[长度(x)-(4:0)])), 复制=1e6))
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]
>>>
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
>
The question is related to time series analysis btw where it is often useful to work only on recent data.
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
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
benchmarking code :
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屋!