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)
First of all, create a list. Then, use tail function with sapply function to extract the last value of all elements in the list.
To find the last element of the vector we can also use tail() function.
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().
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).
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)
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
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