The fastest way to find the transition from positive to negative in a vector in R

I have a vector containing both positive and negative values. For example, something like

x = c(1,2,1,-2,-3,3,-4,5,1,1,-3)

And now I want to note the indices of the vector where the value changes from positive to negative or negative to positive. So, in the example above, I would like something index vector that looks something like this.

y=c(0,0,0,1,0,1,1,1,0,0,1)

I do this in R, so if possible, I would like to avoid using for-loops.

+4
source share
2 answers

I think this should work:

+(c(0, diff(sign(x))) != 0)
#[1] 0 0 0 1 0 1 1 1 0 0 1

all.equal(+(c(0, diff(sign(x))) != 0), y)
#[1] TRUE
+3
source

Here is one way:

yy = rep(0, length(x))
yy[with(rle(sign(x)),{ p = cumsum(c(1,lengths)); p[ -c(1,length(p)) ] })] = 1

all.equal(yy,y) # TRUE

... which turned out to be more confusing than I expected at the beginning.

+2

Source: https://habr.com/ru/post/1626056/


All Articles