Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing the last element of a vector

Tags:

r

vector

subset

I have a pretty straightforward problem which is giving me grief despite a couple of hours of hair-wringing, so I thought I'd ask your help. I am looking for a straightforward way to return a vector which contains only the last element of some original vector.

This is my original vector, 'a':

a<-c(0,0,1,0,0,1,0,0,1,0)

I want to produce the vector 'b', which is of the same length as 'a', and carries only its last nonmissing element. In other words,

b = (0,0,0,0,0,0,0,0,1,0)

I have been able to do this by building a loop running backwards from the end of vector 'a' to its first element, but that seems decidedly inelegant. I'm sure there's a better way.

In case anyone is curious, the larger issue: I am trying to change a value of one vector where it corresponds to the last nonmissing element of another vector.

Thanks very much for any help.

like image 613
daanoo Avatar asked Mar 19 '15 20:03

daanoo


People also ask

How will you extract the last element from the vector?

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

How do I get the last element in C++?

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 you remove the end of a vector?

The standard solution to remove an element from a vector is with the std::vector::erase function. It takes an iterator to the position where the element needs to be deleted. To delete an element at the end of a vector, pass an iterator pointing to the last element in the vector.


2 Answers

This is just for fun as a one-liner:

`[<-`(a, rev(which(as.logical(a)))[-1], 0)
## [1] 0 0 0 0 0 0 0 0 1 0

And a slightly different version:

`[<-`(integer(length = length(a)), rev(which(a != 0))[1], 1)
 ## [1] 0 0 0 0 0 0 0 0 1 0
like image 84
Thomas Avatar answered Oct 04 '22 08:10

Thomas


I believe this should work as well

ifelse(cumsum(a)==sum(a), a, 0)
# [1] 0 0 0 0 0 0 0 0 1 0

This assumes that "missing" values are zeros and non-missing values are 1's. If you have values other than 1's, you would do

ifelse(cumsum(a!=0)==sum(a!=0), a, 0)
like image 33
MrFlick Avatar answered Oct 04 '22 07:10

MrFlick