Мы можем преобразовать значения времени в модуль 1200, чтобы найти точку отсечения, где diff
меньше нуля. Остальное можно сделать в Map
.
cp <- which(c(0, diff(as.numeric(gsub("\\D", "", df$time)) %% 1200)) < 0)
df$time <- unlist(Map(paste0, list(df$time[1:(cp-1)], df$time[cp:nrow(df)]), c("am", "pm")))
df
# id time
# 1 1 12:20am
# 2 2 12:40am
# 3 3 1:00am
# 4 4 1:20am
# 5 5 2:00am
# 6 6 3:00am
# 7 7 3:15am
# 8 8 4:00am
# 9 9 7:00am
# 10 10 11:00am
# 11 11 12:00pm
# 12 12 12:20pm
# 13 13 12:40pm
# 14 14 1:00pm
# 15 15 1:30pm
# 16 16 3:00pm
# 17 17 4:00pm
# 18 18 4:30pm
# 19 19 5:00pm
# 20 20 5:15pm
# 21 21 8:00pm
# 22 22 10:00pm
Данные
df <- structure(list(id = 1:22, time = c("12:20", "12:40", "1:00",
"1:20", "2:00", "3:00", "3:15", "4:00", "7:00", "11:00", "12:00",
"12:20", "12:40", "1:00", "1:30", "3:00", "4:00", "4:30", "5:00",
"5:15", "8:00", "10:00")), row.names = c(NA, -22L), class = "data.frame")