The most efficient way to select the final element of an array?

I am looking for the most efficient way (i.e. pressing smaller keys) to index 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 only one command.

In the above example, I could use

 b <- a[length(a)] 

but I wonder if something shorter exists.

Let me select part of an array, for example

 a <- seq(from = 1, to = 10, by = 1) b <- a[3:length(a)] 

Is there a shorter way to do this?

+6
source share
2 answers

In the first case, you can use:

 > tail(a, 1) [1] 3 

Not that it really was considered 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 does not have an inplace statement or syntactic sugar for the end of a vector or array, in the sense of something that evaluates to the end of the array. You can use length() .

+9
source

Use tail() to get the end of the object:

 x <- 1:100 

By default, tail() returns 6 elements ...

 tail(x) [1] 95 96 97 98 99 100 

... but you can change this:

 tail(x, 10) [1] 91 92 93 94 95 96 97 98 99 100 

Similarly, to get the first elements of head() :

 head(x, 7) [1] 1 2 3 4 5 6 7 
+6
source

Source: https://habr.com/ru/post/922823/


All Articles