George
George

Reputation: 5681

count number of transitions from 0 to 1 and indices where 1 first appears

I have the following data:

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

I want to measure the number of transitions from 0 to 1. So, in the above example it should count 1.

Also, I want to find the indices where the first occurrence of 1 appears. So, it should be [1, 9]

In this example:

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

it should still be 1 since only one time we transited from 0 to 1. the indices should be [1, 9]

In the last :

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

it should count 2. the indices should be [1, 9, 15]

Upvotes: 1

Views: 284

Answers (2)

tmfmnk
tmfmnk

Reputation: 40051

For the first part, you can do:

sum(diff(x) == 1)

[1] 2

For the second part:

c(which.max(x == 1), which(diff(x) == 1) + 1)

[1]  1  9 15

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 389135

Number of transitions between 0 and 1 :

x <- c(1,1,1,1,1,0,0,0,1,1,1,0,0,0,1,1,1)
sum(head(x, -1) == 0 & tail(x, -1) == 1)
#[1] 2

Indices where the first occurrence of 1 appears

with(rle(x), cumsum(lengths)[values == 1] - lengths[values == 1] + 1)
#[1]  1  9 15

Upvotes: 1

Related Questions