假设我有一个时间戳数据帧,其中包含当时售出的相应门票数量。
Timestamp ticket_count
(time) (int)
1 2016-01-01 05:30:00 1
2 2016-01-01 05:32:00 1
3 2016-01-01 05:38:00 1
4 2016-01-01 05:46:00 1
5 2016-01-01 05:47:00 1
6 2016-01-01 06:07:00 1
7 2016-01-01 06:13:00 2
8 2016-01-01 06:21:00 1
9 2016-01-01 06:22:00 1
10 2016-01-01 06:25:00 1
我想知道如何计算所有门票在一定时间内售出的门票数量。例如,我想计算所有门票后15分钟内售出的门票数量。在这种情况下,第一排将有三张票,第二排将有四张票,依此类推。
理想情况下,我正在寻找 dplyr 解决方案,因为我想为多个具有以下功能的商店执行此操作group_by()
功能。但是,我在弄清楚如何保持给定行的每个时间戳固定,同时通过 dplyr 语法搜索所有时间戳时遇到了一些麻烦。
In the 当前开发版本 https://github.com/Rdatatable/data.table/wiki/Installation of data.table
,v1.9.7,non-equi
连接已实施。假设你的data.frame
叫做df
和Timestamp
列是POSIXct
type:
require(data.table) # v1.9.7+
window = 15L # minutes
(counts = setDT(df)[.(t=Timestamp+window*60L), on=.(Timestamp<t),
.(counts=sum(ticket_count)), by=.EACHI]$counts)
# [1] 3 4 5 5 5 9 11 11 11 11
# add that as a column to original data.table by reference
df[, counts := counts]
对于中的每一行t
,所有行,其中df$Timestamp < that_row
已获取。和by=.EACHI
指示表达式sum(ticket_count)
为每一行运行t
。这给出了您想要的结果。
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)