Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorized entry and exit

Tags:

r

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?

like image 896
user1234440 Avatar asked Sep 26 '13 02:09

user1234440


1 Answers

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
like image 78
Ferdinand.kraft Avatar answered Dec 05 '22 03:12

Ferdinand.kraft