r - 在 R 中识别时间窗口内的事件
问题描述
我需要确定在 60 秒内发生的一系列事件(最多 3 个事件)。
这里有 IN 数据
IN<-read.table(header = FALSE, text = "
2018-06-01_04:29:47
2018-06-01_05:44:41
2018-06-01_05:44:43
2018-06-01_05:44:45
2018-06-01_05:57:54
2018-06-01_05:57:56
2018-06-01_05:57:58
2018-06-01_08:10:35
2018-06-01_08:41:20
2018-06-01_08:41:22
2018-06-01_08:41:24
2018-06-01_08:52:01
2018-06-01_09:02:13
2018-06-01_09:22:45", quote="\n",col.names="time")
IN$time<-as.POSIXct(IN$time, "%Y-%m-%d_%H:%M:%S",tz="")
这里有所需的输出
OUT<-read.table(header = FALSE, text = "
2018-06-01_04:29:47 1
2018-06-01_05:44:41 1
2018-06-01_05:44:43 2
2018-06-01_05:44:45 3
2018-06-01_05:57:54 1
2018-06-01_05:57:56 2
2018-06-01_05:57:58 3
2018-06-01_08:10:35 1
2018-06-01_08:41:20 1
2018-06-01_08:41:22 2
2018-06-01_08:41:24 3
2018-06-01_08:52:01 1
2018-06-01_09:02:13 1
2018-06-01_09:22:45 1
",quote="\n",col.names=c("time","response"))
我已经搜索过类似的问题,但没有成功。我想函数 diff 是解决这个问题的第一步,
response<-as.numeric(diff(IN$time)>60)
但我不知道如何继续获得所需的输出。
任何帮助将不胜感激。
解决方案
这是使用 、 和 包的dplyr
解决magrittr
方案lubridate
。
IN<-read.table(header = FALSE, text = "2018-06-01_04:29:47
2018-06-01_05:44:41
2018-06-01_05:44:43
2018-06-01_05:44:45
2018-06-01_05:57:54
2018-06-01_05:57:56
2018-06-01_05:57:58
2018-06-01_08:10:35
2018-06-01_08:41:20
2018-06-01_08:41:22
2018-06-01_08:41:24
2018-06-01_08:52:01
2018-06-01_09:02:13
2018-06-01_09:22:45", quote="\n",col.names="time")
IN$time<-as.POSIXct(IN$time, "%Y-%m-%d_%H:%M:%S",tz="")
我删除了输入数据框的第一行空白,因为它会导致问题。以下函数在给定之前 60 秒内将数据框过滤为那些元素,ref_time
并使用nrow
.
event_count <- function(ref_time){
IN %>% filter(time %within% interval(ref_time - 60, ref_time)) %>% nrow
}
在这里,我以逐行方式应用该函数,记录计数并根据时间排序。(可能没有必要......)使用来自magrittr
.
IN %<>%
rowwise() %>%
mutate(counts = event_count(time)) %>%
arrange(time)
最后,结果。
# A tibble: 14 x 2
# time counts
# <dttm> <int>
# 1 2018-06-01 04:29:47 1
# 2 2018-06-01 05:44:41 1
# 3 2018-06-01 05:44:43 2
# 4 2018-06-01 05:44:45 3
# 5 2018-06-01 05:57:54 1
# 6 2018-06-01 05:57:56 2
# 7 2018-06-01 05:57:58 3
# 8 2018-06-01 08:10:35 1
# 9 2018-06-01 08:41:20 1
# 10 2018-06-01 08:41:22 2
# 11 2018-06-01 08:41:24 3
# 12 2018-06-01 08:52:01 1
# 13 2018-06-01 09:02:13 1
# 14 2018-06-01 09:22:45 1
我认为@PoGibas 所暗示的是出于某种原因,2018-06-01 05:57:54
输入数据框中的时间有两个条目。我不确定第二个来自哪里......
编辑:这是读取表中的新行搞砸了。
EDIT²:这最多返回 3...
event_count <- function(ref_time){
min(IN %>% filter(time %within% interval(ref_time - 60, ref_time)) %>% nrow, 3)
}
推荐阅读
- machine-learning - 处理逻辑回归的 NaN(缺失)值 - 最佳实践?
- elasticsearch - Elastisearch 查询过滤器
- docker - 为什么我需要处于 Swarm 模式才能使用 Docker 机密?
- javascript - 我可以使用正则表达式捕获组来防止该组的连续匹配吗?
- reactjs - 仅在条件为真时测试显示按钮
- sql - 插入语句 Oracle
- mysql - 我试图了解如何使用 TFDStoredProc(FireDac 组件)填充 TIWDBGrid(IntraWeb 组件)
- python - Python - “石头剪刀布”逻辑条件的简化
- javascript - 无法读取未定义的属性“_header”
- r - 意外的循环行为将 ggplot2 参数传递给列表