计算上一个时间段内的事件数

时间:2020-02-04 03:37:48

标签: r events running-total cumsum

我试图创建一个变量(在下面的数据中组成一个“ events60”,该变量保留过去事件的“运行中”计数(在本示例中为60分钟,但可以是任意),因此,它保持了“前一个小时发生了多少事件”的计数。

我正在用cumsum,rle,diff等进行缓慢的处理,但我确定有一个更优雅,更快捷的解决方案。它将应用于至少3000万行的数据集,因此循环可能不太有效。

以下示例数据为R格式

structure(list(Performed_DT_TM = structure(c(1508310211, 1508312843,
1508322697, 1508331061, 1508331161, 1508331452, 1508332222, 1508332900,
1508333781, 1508334349, 1508337531, 1508341065, 1508343542, 1508346756,
1508363905, 1508371639, 1508388245, 1508402001, 1508413612, 1508430173,
1508445426, 1508453675), class = c("POSIXct", "POSIXt"), tzone = ""),
time_since_prev_obs = c(0, 43.8666666666667, 164.233333333333,
139.4, 1.66666666666667, 4.85, 12.8333333333333, 11.3, 14.6833333333333,
9.46666666666667, 53.0333333333333, 58.9, 41.2833333333333,
53.5666666666667, 285.816666666667, 128.9, 276.766666666667,
229.266666666667, 193.516666666667, 276.016666666667, 254.216666666667,
137.483333333333), events60 = c(0, 1, 0, 0, 1, 2, 3, 4, 5,
6, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA,
-22L), class = "data.frame")

当然,任何帮助我们都会感激

欢呼 规范

2 个答案:

答案 0 :(得分:0)

由于数据集很大,因此可以尝试进行滚动联接,然后尝试从data.table进行非等距联接,以提高速度:

setDT(DT)[, Performed_DT_TM := as.POSIXct(Performed_DT_TM, format="%Y-%-%d %T")]
DT[, c("rn", "endtime") := .(.I, Performed_DT_TM - 60L*60L)]

DT[, Last60mins := 
    DT[DT, on=.(Performed_DT_TM=endtime), roll=Inf, i.rn - x.rn - 1L]
]
DT[is.na(Last60mins), Last60mins := fcoalesce(Last60mins, 
    DT[.SD, on=.(Performed_DT_TM>=endtime, Performed_DT_TM<Performed_DT_TM), .N, by=.EACHI]$N)
]
DT

数据:

library(data.table)
DT <- structure(list(Performed_DT_TM = structure(c(1508310211, 1508312843,
    1508322697, 1508331061, 1508331161, 1508331452, 1508332222, 1508332900,
    1508333781, 1508334349, 1508337531, 1508341065, 1508343542, 1508346756,
    1508363905, 1508371639, 1508388245, 1508402001, 1508413612, 1508430173,
    1508445426, 1508453675), class = c("POSIXct", "POSIXt"), tzone = ""),
    time_since_prev_obs = c(0, 43.8666666666667, 164.233333333333,
        139.4, 1.66666666666667, 4.85, 12.8333333333333, 11.3, 14.6833333333333,
        9.46666666666667, 53.0333333333333, 58.9, 41.2833333333333,
        53.5666666666667, 285.816666666667, 128.9, 276.766666666667,
        229.266666666667, 193.516666666667, 276.016666666667, 254.216666666667,
        137.483333333333), events60 = c(0, 1, 0, 0, 1, 2, 3, 4, 5,
            6, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA,
                -22L), class = "data.frame")

答案 1 :(得分:0)

在Base R中,您可以执行以下操作:

 m <- outer(df$Performed_DT_TM,df$Performed_DT_TM,"-")
 c(0,rowsum(as.numeric(m[lower.tri(m)]<3600),row(m)[lower.tri(m)]))
 [1] 0 1 0 0 1 2 3 4 5 6 1 1 1 1 0 0 0 0 0 0 0 0
相关问题