Search code examples
pythonrtidyverseintervalstibble

Turn a time-point column into intervals


I have a tibble storing time-point data:

data.frame(Time = c(0, 1, 2, 3, 4), readings = c(123, 234, 145, 234, 121))

and I would like to turn it into a table like the following:

From To Initial End
0 1 123 234
1 2 234 145
2 3 145 234
3 4 234 121
... ... ... ...

I prefer to accomplish it in R/ tidyverse, but if python can do it in a much simpler way, I can also adopt some python codes. Thanks!


Solution

  • Does this work:

    library(dplyr)
    
    df %>% mutate(To = lead(Time), End = lead(readings)) %>% 
           select('From' = Time, To, 'Initial' = readings, End)
      From To Initial End
    1    0  1     123 234
    2    1  2     234 145
    3    2  3     145 234
    4    3  4     234 121