【问题标题】:data.table: count rows within time moving windowdata.table:计算时间移动​​窗口内的行数
【发布时间】:2018-03-19 08:08:20
【问题描述】:
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"))

对于每一行,我想计算在此行时间之前过去 10 分钟的窗口内具有相同“col1”值和时间的行数(包括)

我运行下一个代码:

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

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    一个可能的解决方案:

    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-语句未正确指定:您需要用, 而不是&amp; 分隔连接条件。例如:on = .(col1, col2 &gt;= t1, col2 &lt;= t2)
    • 使用by = .EACHI 获取每一行的结果。

    另一种方法:

    df[, counts := .SD[.(col1 = col1, t1 = col2 - gap * 60L, t2 = col2)
                       , on = .(col1, col2 >= t1, col2 <= t2)
                       , .N, by = .EACHI]$N][]
    

    给出相同的结果。

    【讨论】:

    • 有时 data.table 解决方案让我大吃一惊。
    猜你喜欢
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多