2

I have a dataset where I am trying to find the first instance in a consecutive set of rows that are identical. So let's say given this dataset:

df <- data.frame(trial = c(1:16), DV = c(2, 3, 2, 3, 3, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 1))

If I were looking for the first integer in df$DV to repeat itself 5 times (for example), it would spit out "4".

I've tried a few things using the solutions found here (R: Selecting first of n consecutive rows above a certain threshold value), which is a similar problem, but I'm stuck. Any suggestions?

Thanks for your help in advance!

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
alexd
  • 57
  • 4

1 Answers1

4

This does it

with(rle(df$DV), values[which(lengths >= 5)[1]])

If there is no consecutive chunks with a length >= 5, you get NA.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • Ha! I was thinking about it way too hard. This is a simple, elegant solution. Thank you! – alexd Jun 18 '17 at 16:37