Search code examples
rdataframetimelag

Find lag between non-consecutive observations


Let's suppose I have the following data.frame:

df = data.frame(x = c(1,3,5,6,8,11,15,16,18,20,21,22,24,25,40,50,54,55,70,71,100,101,102,103))

I need to find the lag between non-consecutive x values. This means authomatically doing: 3-1, 5-3, 8-6, 11-8, 15-11, 18-16, 20-18, 24-22, etc...

Any suggestion?


Solution

  • We can take difference between all values but keep only those values which are not consecutive

    with(df, diff(x)[diff(x) != 1])
    #[1]  2  2  2  3  4  2  2  2 15 10  4 15 29