I have a time series and I have a specific requirement for adding a new variable.
Here is some data
dput(df)
structure(list(Time = structure(c(1567423339.229, 1567423399.018,
1567424218.867, 1567425478.666, 1567425498.883, 1567426519.008,
1567429378.848, 1567429398.979, 1567429978.723, 1567431218.909
), tzone = "", class = c("POSIXct", "POSIXt")), RaceNum = c("1",
"1", "1", "1", "1", "1", "2", "2", "2", "2")), class = "data.frame", row.names = c(NA,
-10L))
What I have tried to do unseussesfully using case_when or ifelse is to assign d
on a 1:nrow
basis unless the next time series event is within 1 minute then it takes the previous variable and adds a b
to it. As you can see the numbering starts again whne RaceNum
changes. I was splitting the df by RaceNum
then cbind
back together once I had established d
.
Here is the expected result
dput(df2)
structure(list(Time = structure(c(1567423339.229, 1567423399.018,
1567424218.867, 1567425478.666, 1567425498.883, 1567426519.008,
1567429378.848, 1567429398.979, 1567429978.723, 1567431218.909
), tzone = "", class = c("POSIXct", "POSIXt")), RaceNum = c("1",
"1", "1", "1", "1", "1", "2", "2", "2", "2"), d = c("1", "1b",
"2", "3", "3b", "4", "1", "1b", "2", "3")), class = "data.frame", row.names = c(NA,
-10L))
CodePudding user response:
- For each
RaceNum
create a variable which increments when the difference between consecutive records is greater than 1 minute. - For each group (
d
) pasteletters
to group number.
library(dplyr)
df %>%
group_by(RaceNum) %>%
mutate(d = cumsum(difftime(Time, lag(Time, default = first(Time)),
units = 'min') > 1) 1) %>%
group_by(d, .add = TRUE) %>%
mutate(d = paste0(d, letters[row_number()]),
#For 1st row remove a from 1a, 2a etc.
d = ifelse(row_number() == 1, sub('a', '', d), d)) %>%
ungroup
# Time RaceNum d
# <dttm> <chr> <chr>
# 1 2019-09-02 19:22:19 1 1
# 2 2019-09-02 19:23:19 1 1b
# 3 2019-09-02 19:36:58 1 2
# 4 2019-09-02 19:57:58 1 3
# 5 2019-09-02 19:58:18 1 3b
# 6 2019-09-02 20:15:19 1 4
# 7 2019-09-02 21:02:58 2 1
# 8 2019-09-02 21:03:18 2 1b
# 9 2019-09-02 21:12:58 2 2
#10 2019-09-02 21:33:38 2 3