如何使用 R 检测系列数据中的间隙

Mat*_*ing 4 r

我有一个设备,可以将定期(大约每 5 分钟)行插入到状态表中。每行都被视为一个状态事件并带有时间戳。我需要检测 2 个状态事件何时发生间隔超过 10 分钟。

虽然我可以使用循环解决方案,但它看起来不太优雅,我正在寻找另一个答案。数据库中的表可以简化为:

12:01:00,状态,可以
12:06:31,状态,可以
12:12:02,状态,可以
13:15:43,状态,可以
13,20:33,状态,可以

所以我想检测第三个和第四个状态行之间有 1:03:41 的差距。不用说我有很多数据需要处理。

arv*_*000 5

如果您使用 POSIXct 格式的时间戳数据,则只需进行简单的减法即可获得时间差。

因为 R 是向量化的,所以不需要循环——它只是一个向量减去另一个向量

然后很容易测试差距是否超过某个阈值。

# here's a data frame with a bunch of time stamps
my_dat <- data.frame(time=Sys.time() + sort(runif(10, 100, 600)))

# Take rows 1 to n-1 and subtract rows 2 to n:
my_dat$gap <- c(NA, with(my_dat, time[-1] - time[-nrow(my_dat)]))

# now, how often was the gap more than some amount of time?
gap_threshold <- 30 # let's say, 30 seconds
my_dat$over_thresh <- my_dat$gap > gap_threshold
my_dat

# result: timestamp, difference from prior row in seconds, threshold test result
# > my_dat
#                   time       gap over_thresh
# 1  2015-05-28 16:28:05        NA          NA
# 2  2015-05-28 16:28:46 40.852095        TRUE
# 3  2015-05-28 16:29:35 49.060379        TRUE
# 4  2015-05-28 16:29:55 20.290983       FALSE
# 5  2015-05-28 16:30:02  6.580322       FALSE
# 6  2015-05-28 16:30:34 32.039323        TRUE
# 7  2015-05-28 16:30:58 24.601907       FALSE
# 8  2015-05-28 16:31:16 17.761954       FALSE
# 9  2015-05-28 16:31:51 34.794329        TRUE
# 10 2015-05-28 16:32:35 44.213900        TRUE
Run Code Online (Sandbox Code Playgroud)