我有一组电子邮件地址和日期,这些电子邮件地址已添加到表格中.对于不同的日期,可以有多个电子邮件地址条目.例如,如果我有下面的数据集.我希望得到我们在所述日期和3天前之间的不同电子邮件的日期和计数.
Date | email
-------+----------------
1/1/12 | test@test.com
1/1/12 | test1@test.com
1/1/12 | test2@test.com
1/2/12 | test1@test.com
1/2/12 | test2@test.com
1/3/12 | test@test.com
1/4/12 | test@test.com
1/5/12 | test@test.com
1/5/12 | test@test.com
1/6/12 | test@test.com
1/6/12 | test@test.com
1/6/12 | test1@test.com
Run Code Online (Sandbox Code Playgroud)
如果我们使用3的日期,结果集看起来会像这样
date | count(distinct email)
-------+------
1/1/12 | 3
1/2/12 | 3
1/3/12 | 3
1/4/12 | 3
1/5/12 | 2
1/6/12 | 2
Run Code Online (Sandbox Code Playgroud)
我可以使用下面的查询获得日期范围的明确计数,但是希望按天计算范围,这样我就不必手动更新数百个日期的范围.
select test.date, count(distinct test.email)
from test_table as test
where test.date between '2012-01-01' and '2012-05-08' …Run Code Online (Sandbox Code Playgroud) 我正在尝试添加新列data.table,其中行中的值取决于行中值的相对关系.更确切地说,如果一行中有一个值X,我想知道在X-30中有多少其他值在同一列(和组)中.
就是这样:
DT<-data.table(
X = c(1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 1, 1),
Y = c(100, 101, 133, 134, 150, 156, 190, 200, 201, 230, 233, 234),
Z = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
Run Code Online (Sandbox Code Playgroud)
我想获得一个新列,其值为:
N <- c(0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 2)
Run Code Online (Sandbox Code Playgroud)
我尝试了以下内容,但我没有得到我可以使用的结果:
DT[,list(Y,num=cumsum(Y[-.I]>DT[.I,Y]-30),Z),by=.(X)]
Run Code Online (Sandbox Code Playgroud)
任何想法如何做到这一点?