# 02 FB Aggregate by Age Group.r

#  (1) Select Time Frame
#  (2) Calculate the aggregates for that time Frame
#        * By age Group
#        * Total
#  (3) Select an Age Group
#  (4) Select (many/a) Campaign(s)
#  (5) Plot The Age Group & Campaign + Totals



# NOT BEING USED FOR NOW.  
# x - ## Identify the important columns
# x - cols.mets  <- c("Spend", 
# x -                 "Impressions", "Soc.Impressions", "Reach", "Soc.Reach", "Freq", 
# x -                 "Clicks", "Soc.Clicks", "uClicks", "Clicks.Link", 
# x -                 "Actions", "PeopleActioning", 
# x -                 "EventResponse",
# x -                 "Likes.Page",  "Likes.Post", 
# x -                 "Engagement.Page", "Engagement.Post",
# x -                 "Comments.Post", "Shares.post", 
# x -                 "Mentions.Page", 
# x -                 "Views.PagePhoto", "Views.VideoPlays", 
# x -                 "Conversion.Website", "Conversion.OtherWebsite"
# x -                 )
# x - cols.calcs <- c("CTR", "CPC", "CPM", "uCTR",  "uCPM", "uCPC")
# x - cols.demog <- c("Age", "Gender") 
# x - cols.info.main  <- c("CampaignID", "AdID") 
# x - cols.info.extra <- c("Campaign",   "Ad")
# x - cols.date <- c("Date", "Year")
# x - cols.info <- sort(c(cols.info.main, cols.info.extra))
# x - 
# x - 
# x - ## Aggregate by demographic
# x - fb.agg.demog <- aggBy(DT=fb, byCols=c("Age", "Campaign"), DateIn=TRUE, verbose=TRUE, cols.agging=cols.mets)


# ----------------------------------------- #
#     WHETHER TO INCLUDE DATE OR NOT        #
# ----------------------------------------- #
          # Set this to NULL   for Out
          #          to "Date" for In
          DateInOrOut <- NULL # "Date"
# ----------------------------------------- #

# ----------------------------------------- #
### SIMPLE
cols.simple.mets <- c("Impressions", "Clicks", "Spend", "Actions")
fb.agg <- aggBy(DT=fb, byCols=c("Age", "Campaign"), DateIn=!is.null(DateInOrOut), DateOut=is.null(DateInOrOut), verbose=FALSE, cols.agging=cols.simple.mets)
# ----------------------------------------- #


## Add rows for total values, for cache'ing the aggregates
fb.agg <- 
  rbindFactorCheck(silent=TRUE, l=list(
        fb.agg, 
        computeTotals(fb.agg, "Age", by=c(DateInOrOut, "Campaign"), col.mets=cols.simple.mets, reorder=TRUE), 
        computeTotals(fb.agg, "Campaign", by=c(DateInOrOut, "Age"), col.mets=cols.simple.mets, reorder=TRUE),
        computeTotals(fb.agg, c("Age", "Campaign"), by=c(DateInOrOut), col.mets=cols.simple.mets, reorder=TRUE)
    ))

# Calculate the percent of impressions per group, for each Campaign
fb.agg[Age != "TOTAL", 
       Perc.Impr.PerAge := 100 *
          round(tapply(Impressions, Age, sum) / sum(Impressions), 6)
      , by=list(Campaign)]

## ------------------------------------ ##
##  Calculate key metric summaries      ##
## ------------------------------------ ##
calcCTR_(fb.agg)
calcCPC_(fb.agg, Cost="Spend")
calcCPM_(fb.agg, Cost="Spend")

calcCTR_(fb.agg, Click="Actions", assignTo="ATR")
calcCPC_(fb.agg, Cost="Spend", Click="Actions", assignTo="CPA")

# drop the individual metric columns
# fb.agg[, c(cols.simple.mets) := NULL]
## ------------------------------------ ##

# Drop 0-Spend with few views
fb.agg <- fb.agg[!(Spend == 0 & Clicks == 0 & Impressions < 2500)]


# make the demog columns into factors
fb.agg[, c("Age", "Campaign") := list(factor(Age), factor(Campaign))]
fb.agg[ , Age := relevel(Age, "TOTAL")]

fb.agg[ , CampShort := cleanCampName(Campaign, substrLen=27)]



## Add Cuts & Labels for the Cost columns 
# ----------------------------------- #
  addCutCol(fb.agg, "CPC", "linear", asDollars=TRUE, noWarnOnChar=TRUE)
  addCutCol(fb.agg, "CPA", "linear", asDollars=TRUE, noWarnOnChar=TRUE)
  addCutCol(fb.agg, "CPM", "linear", asDollars=TRUE, noWarnOnChar=TRUE)
  addCutCol(fb.agg, "Spend", "log",  asDollars=TRUE, noWarnOnChar=FALSE, dollarsDec=0
                     , useRoundLeft=TRUE, breaks=c(-1,5,10^seq(1, 4, by=.5)))
# ----------------------------------- #


# reshape
## ------------------------------------ ##
  datKeyCols <- c("Campaign", "Age", DateInOrOut)
  id.vars <- c(DateInOrOut,"Age","Campaign", "Perc.Impr.PerAge", cols.simple.mets)
  aggvarsKeeping <- c("CPC", "CPM")
  measure.vars <- c("CTR", "ATR")
  dat <- data.table( melt(fb.agg, id.vars=id.vars), key=datKeyCols )
## ------------------------------------ ##

## This gives the totals, by date
tot <- dat[.("TOTAL", "TOTAL")]   # not sure what I want to do with tot yet
tot <- dat[(Age=="TOTAL" | Campaign=="TOTAL")]
tot[, setdiff(id.vars, key(dat)) := NULL]
setkeyv(tot, c(DateInOrOut, "variable"))

## Drop the `TOTAL` rows from the dat DT
dat <- dat[!(Age=="TOTAL" | Campaign=="TOTAL")]
dat[, Age := droplevels(Age)]
dat[, Campaign := droplevels(Campaign)]
setkeyv(dat, datKeyCols)

saveImageTo()



