library(data.table)
df <- data.table(col1 = c('B', 'A', 'A', 'B', 'B', 'B'), col2 = c("2015-03-06 01:37:57", "2015-03-06 01:39:57", "2015-03-06 01:45:28", "2015-03-06 02:31:44", "2015-03-06 03:55:45", "2015-03-06 04:01:40"))
对于每一行,我想计算具有相同值'col1'的行数以及此行时间之前过去10分钟窗口内的时间(包括)
我运行下一个代码:
df$col2 <- as_datetime(df$col2)
window = 10L
(counts = setDT(df)[.(t1=col2-window*60L, t2=col2), on=.((col2>=t1) & (col2<=t2)),
.(counts=.N), by=col1]$counts)
df[, counts := counts]
又犯了下一个错误:
Error in `[.data.table`(setDT(df), .(t1 = col2 - window * 60L, t2 = col2), : Column(s) [(col2] not found in x
我想要下一个结果:
col1 col2 counts
B 2015-03-06 01:37:57 1
A 2015-03-06 01:39:57 1
A 2015-03-06 01:45:28 2
B 2015-03-06 02:31:44 1
B 2015-03-06 03:55:45 1
B 2015-03-06 04:01:40 2
答案 0 :(得分:4)
可能的解决方案:
df[.(col1 = col1, t1 = col2 - gap * 60L, t2 = col2)
, on = .(col1, col2 >= t1, col2 <= t2)
, .(counts = .N), by = .EACHI][, (2) := NULL][]
给出:
col1 col2 counts 1: B 2015-03-06 01:37:57 1 2: A 2015-03-06 01:39:57 1 3: A 2015-03-06 01:45:28 2 4: B 2015-03-06 02:31:44 1 5: B 2015-03-06 03:55:45 1 6: B 2015-03-06 04:01:40 2
关于您的方法的几点说明:
setDT
,因为您已使用df
构建了data.table(...)
。on
- 未正确指定语句:您需要将加入条件与,
分开,而不是&
。例如:on = .(col1, col2 >= t1, col2 <= t2)
by = .EACHI
获取每行的结果。另一种方法:
df[, counts := .SD[.(col1 = col1, t1 = col2 - gap * 60L, t2 = col2)
, on = .(col1, col2 >= t1, col2 <= t2)
, .N, by = .EACHI]$N][]
给出相同的结果。