I have an activity
col and their start and end time in col time
.
How can I create another tibble with three cols - activity
, start_time
and end_time
library(dplyr)
time <- sort(sample(x = 1:100, size = 12, replace = FALSE))
activity <- c(rep("A", 2), rep("B", 2), rep("C", 2), rep("B", 2), rep("A", 2), rep("C", 2))
tbl <- tibble(time, activity)
CodePudding user response:
Is this what you're looking for? lead(time)
computes the next value in the time
variable, and slice
removes one every second rows.
library(dplyr)
tbl %>% mutate(start_time = time,
end_time = lead(time)) %>%
slice(seq(1, n(), by =2))
# A tibble: 6 x 4
time activity start_time end_time
<int> <chr> <int> <int>
1 3 A 3 7
2 12 B 12 19
3 21 C 21 25
4 62 B 62 65
5 86 A 86 88
6 91 C 91 97