Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to select ending item of an array?

Tags:

r

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?

like image 799
Lisa Ann Avatar asked Aug 14 '12 10:08

Lisa Ann


People also ask

How do you find the last element of an array?

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.

How do you end an array?

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.

Which expression can be used to access the last element of an 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.

Is list more efficient than array?

From a memory allocation point of view, linked lists are more efficient than arrays.


1 Answers

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.

like image 134
Gavin Simpson Avatar answered Sep 30 '22 06:09

Gavin Simpson