split vector based on TRUE FALSE statement

Viewed 48

I want to count the lengths of consecutive negative numbers appearing in a vector. split seems to be the way to do this, but I am having trouble specifying where to make the splits. For example, given:

dat<-c(-1,-1,-1,-1,1,1,1,-1,-1,1,1,1)

I am expecting split to return a list of length 8, where the first element has length 4, and the fifth element has length 2, indicating the lengths of consecutive sequences of negative numbers. I have tried:

split(dat, cumsum(dat > 0))

which results in:

$`0`
[1] -1 -1 -1 -1

$`1`
[1] 1

$`2`
[1] 1

$`3`
[1]  1 -1 -1

$`4`
[1] 1

$`5`
[1] 1

$`6`
[1] 1

This is not correct. My problem is with using cumsum, since this is returning:

[1] 0 0 0 0 1 2 3 3 3 4 5 6

when I want it to return:

[1] 0 0 0 0 1 2 3 4 4 5 6 7

cumsum seems the way to do this, but perhaps I need to look elsewhere.

1 Answers

Perhaps this helps in splitting into a list of length 8

library(data.table)
split(dat, rleid(cumsum(dat > 0) + (dat > 0)))

-output

$`1`
[1] -1 -1 -1 -1

$`2`
[1] 1

$`3`
[1] 1

$`4`
[1] 1

$`5`
[1] -1 -1

$`6`
[1] 1

$`7`
[1] 1

$`8`
[1] 1
Related