Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last element in a list in R

Tags:

list

r

sapply

I want to get the every last element in a list. I have found that by using sapply function, the first element can be obtained.

sapply(a,`[`,1)

However, I don't actually understantd what is the meaning of [, and how to get the last element in a similar way. This code doesn't work.

sapply(a,`]`,1)
like image 329
Roy Avatar asked Jun 22 '18 07:06

Roy


People also ask

How do I get the last element in a list in R?

First of all, create a list. Then, use tail function with sapply function to extract the last value of all elements in the list.

How do I retrieve the last element of a vector in R?

To find the last element of the vector we can also use tail() function.

How do you find the last value of a vector?

In C++ vectors, we can access last element using size of vector using following ways. 2) Using back() We can access and modify last value using back().

How do I remove the last element of a list in R?

To remove the last elements of a vector, we can use head function with negative sign of the number of values we do not want. For example, if we have a vector of length 200 but we don't want last fifty elements then we can use head(vector_name,-50).


2 Answers

I came here with the same question, and saw that the answer must have been overlooked, but for me @akrun as usual had the answer that worked for me. So in the absence of a correct answer it is:

sapply(a, tail, 1)

like image 68
mattbawn Avatar answered Sep 29 '22 13:09

mattbawn


By using the length of a list/vector:

a[length(a)]

For the last "n"th element:

a[length(a)-n+1]

Example:

a[length(a)-1] #the 2nd last element
a[length(a)-2] #the 3rd last element
a[length(a)-8] #the 9th last element
like image 27
uguros Avatar answered Sep 29 '22 12:09

uguros