Bjorn
Bjorn

Reputation: 97

R: Sum values that are in different parts of vector

I have a number of vectors consisting of 1s and 0s, such as:

[1] x <- c(0, 1, 1, 0, 0, 1)

I would like to count the number of consecutive 1s at different parts of these sequences, and in this instance end up with:

[1] 2 1

I have considered using something like strsplit to split the sequence where there are zeros, though it is a numeric vector so strsplit won't work and ideally I don't want to change back and forth between numeric and character format.

Is there another, simpler, solution to this? Would appreciate any help.

Upvotes: 1

Views: 223

Answers (1)

lmo
lmo

Reputation: 38500

You can split up the value into a vector and use rle like this:

With your original value

x <- 11001

temp <- rle(unlist(strsplit(as.character(x), split="")))

temp$lengths[temp$values == 1]
[1] 2 1

It's a bit simpler when starting with the vector as you don't have to use strsplit and unlist.

x <- c(0, 1, 1, 0, 0, 1)

temp <- rle(x)

temp$lengths[temp$values == 1]
[1] 2 1

Upvotes: 4

Related Questions