I'm looking for the most efficent way (i.e. the lesser keys pressed) to indexing the last element of an array.
Then something like
a <- c(1,2,3)
n <- length(a)
b <- a[n]
should not be used, I would like to use just a single command.
In the example above I could use
b <- a[length(a)]
but I wonder if something shorter does exist.
Let I want to select a part of an array, like
a <- seq(from = 1, to = 10, by = 1)
b <- a[3:length(a)]
Is there a shorter way to do it?
1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.
The end() function moves the internal pointer to, and outputs, the last element in the array. Related methods: current() - returns the value of the current element in an array. next() - moves the internal pointer to, and outputs, the next element in the array.
lastIndexOf() The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.
From a memory allocation point of view, linked lists are more efficient than arrays.
For the first case, you can use:
> tail(a, 1)
[1] 3
Not that that really qualifies as shorter.
For the second example
> tail(a, -2)
[1] 3 4 5 6 7 8 9 10
but in general; no there is nothing shorter. R doesn't have an inplace operator or syntactic sugar for the end of a vector or array, in the sense of something that evaluates to the end of the array. That is what length()
can be used for.
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