Find first sequence of length n in R

Viewed 779

Lets say I have such a data.frame

df <- data.frame(signal = c(0, 0, 1, 0, 1, 1, 0, 1, 1, 1))

What is the best way to to find first signal by the number ones that go in succession n times. For example if n = 1 then my signal would be third element and I would like to get an answer like this:

c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0)

For n=2 answer would be:

c(0, 0, 0, 0, 0, 1, 0, 0, 0, 0)

And for n=3 last element is signal after 3 ones in a row:

c(0, 0, 0, 0, 0, 0, 0, 0, 0, 1)
3 Answers
Related