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.
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().
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.
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
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)
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