I was wondering if there is a vectorized way of returning the following:
I have a vector =
x = c(-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,11,10,9,8,7,6,5,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12)
I want to get a vector of the same length back such that when its crossed above 5 it will set it to 1 (TRUE) until it drops below 0 (FALSE). I am currently doing a for loop which will take forever should the above series have large number of observations.
answer should return:
results = c(0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1)
Any ideas?
With package zoo
, you can use this:
results2 <- na.locf(c(NA,1,0)[(x>=5) + 2*(x<=0) + 1],na.rm=FALSE)
identical(results2, results)
#[1] 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