Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a vector in R based on sign (+/-)

Tags:

r

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!

like image 524
user3022875 Avatar asked Feb 14 '23 02:02

user3022875


2 Answers

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
like image 160
James Avatar answered Feb 16 '23 15:02

James


An alternative to @James's solution is to use sequence and rle:

which(sequence(rle(sign(v))$lengths) == 1)
# [1] 1 3 6
like image 27
A5C1D2H2I1M1N2O1R2T1 Avatar answered Feb 16 '23 16:02

A5C1D2H2I1M1N2O1R2T1