I would like to split a vector based on its sign. I have a vector that looks like:
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 a vector of FIRST index of each group....
So the result I want is vector containing the indicies 1,3,6
I would like this to work if the vector has an arbitrary number of groups of arbitrary size.
Any help?
Thank you!
You can use sign
to pick out the signs, and then diff
to see where this changes.
c(1,which(diff(sign(v))!=0)+1)
[1] 1 3 6
An alternative to @James's solution is to use sequence
and rle
:
which(sequence(rle(sign(v))$lengths) == 1)
# [1] 1 3 6
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