我连续一天都在划船,其中包括几次旅行。我想用不同的代码(唯一ID(来识别每次旅行。每次乘船旅行都可以被检测到,因为连续点之间的周期较大。请注意,时间不是固定的。
例如:
library(dplyr)
rep_data <- data.frame(
t = c(1, 2, 3, 4,5,10, 12, 13,14,15,16, 23, 24,26,28),#this would be the time
expect_output = c(1, 1, 1, 1,1,2, 2, 2,2,2,2, 3, 3,3,3)) # this would be the unique ID of the trip
rep_data <- rep_data %>%
mutate(dif.time = c(t-lag(t,1)),
gp = ifelse(dif.time > 5, 1, 0))
我试过了:
我试过用cumsum HERE
rep_data %>%
mutate(daynum = cumsum(!duplicated(gp)))
我尝试了group_indices另一个
rep_data %>%
group_by(dif.time) %>%
group_indices()
并尝试了cur_group_id。
但我甚至还没有接近解决这个简单的挑战。
expect_output列表示我想要的结果,即在整个期间内三次乘船旅行。
知道怎么去那里吗?,任何帮助都会得到极大的回报
提前非常感谢,
谨致问候,Marta
根据您的数据,您需要得出一些阈值数字,以识别新的行程。然后,您可以获取连续值之间的差值,并在超过阈值时递增序列。
threshold <- 5
rep_data$trip_id <- cumsum(c(TRUE, diff(rep_data$t) >= threshold))
rep_data
# t trip_id
#1 1 1
#2 2 1
#3 3 1
#4 4 1
#5 5 1
#6 10 2
#7 12 2
#8 13 2
#9 14 2
#10 15 2
#11 16 2
#12 23 3
#13 24 3
#14 26 3
#15 28 3