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
一个可能的解决方案:
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
,因为您已经使用data.table(...)
构建了df
。 - 您
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][]
这给出了相同的结果。