作者:Life一切安好 | 2023-09-09 11:56
1> eddi..:
setDT(dt)
dt[, ActivityDate := as.Date(ActivityDate, '%m/%d/%Y')]
# add index to keep track of rows
dt[, idx := .I]
# match the dates we're looking for using a rolling join and extract the row numbers
rr = dt[.(Name = Name, ActivityDate = ActivityDate - 21, refIdx = idx),
.(idx, refIdx), on = c('Name', 'ActivityDate'), roll = -Inf]
# idx refIdx
# 1: 1 1
# 2: 1 2
# 3: 1 3
# 4: 1 4
# 5: 5 5
# 6: 5 6
# 7: 6 7
# 8: 8 8
# 9: 8 9
#10: 8 10
#11: 11 11
#12: 11 12
#13: 12 13
# extract the above rows and count occurrences using dcast
dcast(rr[, {seq = idx:refIdx; dt[seq]}, by = 1:nrow(rr)], nrow ~ ActivityType)
# nrow Email Webinar
#1 1 1 0
#2 2 2 0
#3 3 2 1
#4 4 2 2
#5 5 0 1
#6 6 1 1
#7 7 2 0
#8 8 1 0
#9 9 1 1
#10 10 1 2
#11 11 0 1
#12 12 1 1
#13 13 2 0