Johhn White
Johhn White

Reputation: 59

Index of element with given property based on the rest of the sequence

Hey I have following vector of 0's and 1's:

x = c(0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0)

I want to find an index of the first element from sequence of 1's which length exceeds the length of every subsequent string of 0's. So in my example the solution should be "10", because three last elements of x are: 1, 1, 0 so length of sequence 1, 1 is greater than length of any subsequent string of 0's. How can I do that in R?

Upvotes: 1

Views: 38

Answers (1)

tmfmnk
tmfmnk

Reputation: 39858

One option could be:

which.max(with(rle(x), rep(values * (lengths > c(tail(lengths, - 1), 0)), lengths)))

The results for different x values:

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

[1] 10

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

[1] 5

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

[1] 1

However, this assumes that there is at least one such sequence.

For cases with no sequence fulfilling the criteria:

ind <- with(rle(x), rep(values * (lengths > c(tail(lengths, - 1), NA)), lengths))
if(length(which(ind == 1)) == 0) NA else min(which(ind == 1))

Upvotes: 1

Related Questions