简体   繁体   English

连续时间组 dplyr r-project

[英]groups on continuous time dplyr r-project

I have a continuous day with boat movements, that include several trips.我有一整天的船运动,其中包括几次旅行。 I want to identify each trip with a different code (unique ID).我想用不同的代码(唯一 ID)标识每次旅行。 Each boat trip can be detected because the period between successive points is larger.因为连续点之间的周期较大,所以可以检测到每次乘船旅行。 Note that the time is not regular.请注意,时间不规律。

For example:例如:

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))

I tried:我试过了:

I tried with cumsum HERE我在这里尝试过cumsum

rep_data %>%
  mutate(daynum = cumsum(!duplicated(gp)))

I tried with group_indices another one我尝试了另一个group_indices

rep_data %>%
  group_by(dif.time) %>% 
  group_indices() 

and also tried cur_group_id.并且还尝试了 cur_group_id。

But I am not even close to solve this simple challenge.但我什至还没有接近解决这个简单的挑战。

The column expect_output indicates the result I wanted, that would be three boat trips during the complete period. expect_output 列表示我想要的结果,即整个期间的三趟船之旅。

Any ideia how to get there?任何想法如何到达那里? Any help will be greatly apretiated,任何帮助将不胜感激,

Thank you very much in advance,非常感谢您,

Best regards, Marta最好的问候,玛塔

Based on your data you need to come up with some threshold number which will identify new trip.根据您的数据,您需要提出一些阈值来识别新的行程。 You can then take difference between consecutive values and increment the sequence whenever threshold is crossed.然后,您可以获取连续值之间的差异,并在超过阈值时增加序列。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM