Divide the vector in R based on the sign (+/-)

I would like to break the vector into its sign. I have a vector that looks like this:

v <- c(1, 2,-4,-8 ,-9, 4)

There are 3 groups in the vector. A positive group (index 1 and 2), a negative group (index 3,4,5) and another positive group (index 6). I want to get the FIRST index vector of each group ....

So I want to get a vector containing pointers 1,3,6

I would like this to work if the vector has an arbitrary number of groups of arbitrary size.

Any help?

Thanks!

+4
source share
2 answers

You can use signto select characters and then diffto see where it changes.

c(1,which(diff(sign(v))!=0)+1)
[1] 1 3 6
+5
source

@James sequence rle:

which(sequence(rle(sign(v))$lengths) == 1)
# [1] 1 3 6
+3

All Articles