Home > Software engineering >  Turn a time-point column into intervals
Turn a time-point column into intervals

Time:10-17

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!

CodePudding user response:

We may do this in base R by removing the last row and first row of the dataset and renaming the columns

setNames(cbind(df1[-nrow(df1), ], df1[-1, ]),
     c("From", "Initial", "To", "End"))[c(1, 3, 2, 4)]
  From To Initial End
1    0  1     123 234
2    1  2     234 145
3    2  3     145 234
4    3  4     234 121

CodePudding user response:

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

CodePudding user response:

Here is an alternative dplyr approach: using across

df %>%
  mutate(across(everything(), lead, .names="end_{col}")) %>% 
  select(From=Time, To=end_Time, Initial=readings, End=end_readings)
  From To Initial End
1    0  1     123 234
2    1  2     234 145
3    2  3     145 234
4    3  4     234 121
5    4 NA     121  NA
  • Related