Grab the last element of the vector
I have a very straightforward question. Even after a few hours of trouble, it makes me sad, so I think I'll ask you for help I'm looking for a direct way to return a vector that contains only the last element of an original vector
This is my original vector 'a':
a<-c(0,1,0)
I want to generate a vector 'B', which is the same length as' a ', and takes only its last non missing element In other words,
b = (0,0)
I've been able to do this by building a loop that runs backwards from the end of vector 'a' to the first element, but it doesn't seem so elegant I believe there is a better way
If anyone is curious, the bigger problem is: I try to change the value of one vector, which corresponds to the last non missing element of another vector
Thank you very much for your help
Solution
One option is
b<- numeric(length(a)) b[max(which(a!=0))] <- 1 b #[1] 0 0 0 0 0 0 0 0 1 0