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 like 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.
Method 2: Using Tail() function To find the last element of the vector we can also use tail() function.
R – Vector Length To get length of a vector in R programming, call length() function and pass the vector to it. length() function returns an integer, representing the length of vector.
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) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With