Given the variable
a <- c(1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0)
I would like to mark the last non-zero value to produce a variable that takes value of 0 before the benchmark and 1 after it. In this case
b <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
A simple command that allows to mark the last non-zero value of a a column is
tail(which(a!=0),1)
But how to create the variable I need conditional on such benchmark? Any help would be much appreciated!
One option could be:
+(cumsum(a) == max(cumsum(a)))
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1
Or:
+(cumsum(a) == sum(a))
We can use which to get the position, index where a is 1, wrap with max to return the last position, create a logical vector with sequence of 'a' and coerce to binary (+)
+(seq_along(a) >= max(which(a == 1)))
#[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1
Or use Position
+(seq_along(a) >= Position(function(x) x == 1, a, right = TRUE))
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