This is what my dataframe looks like. The two rightmost columns are my desired columns.These two columns check the condition whether in the last 21 days there is an "Email" ActivityType and whether in the last 21 days there is a "Webinar" ActivityType.
Name ActivityType ActivityDate Email(last21days) Webinar(last21day)**
John Email 1/1/2014 TRUE NA
John Webinar 1/5/2014 TRUE TRUE
John Sale 1/20/2014 TRUE TRUE
John Webinar 3/25/2014 NA TRUE
John Sale 4/1/2014 NA TRUE
John Sale 7/1/2014 NA NA
Tom Email 1/1/2015 TRUE NA
Tom Webinar 1/5/2015 TRUE TRUE
Tom Sale 1/20/2015 TRUE TRUE
Tom Webinar 3/25/2015 NA TRUE
Tom Sale 4/1/2015 NA TRUE
Tom Sale 7/1/2015 NA NA
Based on the help here: Extracting event types from last 21 day window I tried:
df$ActivityDate <- as.Date(df$ActivityDate)
library(data.table)
setDT(df)
setkey(df, Name,ActivityDate)
Elsetemp <- df[, .(Name, ActivityDate, ActivityType)]
df[Elsetemp, `:=`(Email21 = as.logical(which(i.ActivityType == "Email")),
Webinar21 = as.logical(which(i.ActivityType == "Webinar"))),
roll = -21, by = .EACHI]
to no avail as I only get TRUE
s for rows with "Sale". For example, second row where ActivityType = Webinar, both Email21 & Webinar21 should say TRUE. When I am defining last 21 days, I am trying to include that very day when the event happened too.
How about this?
Using rolling joins from
data.table
: