# Starting with 

# 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


tot  # "Date"     "variable"
dat  # "Campaign" "Age"      "Date"  


## Make a list of all KEY values of dat, then grab all Campaigns available
datKeys <- getKeyVals(dat)

campns <- datKeys$Campaign
ages   <- dat[, unique(Age)] 


#  (1) Select Time Frame

dateMin <- as.Date("2013-07-01")
dateMax <- as.Date("2013-09-12")

dates <- seq.Date(from=dateMin, to=dateMax, by=1)
## TODO:  Error check for date range

#  (2) Calculate the aggregates for that time Frame
#        * By age Group
#        * Total

## Already done in the `tot` DT

#  (3) Select an Age Group
## example: 
ages.selected <- ages[c(2)] 

#  (4) Select (many/a) Campaign(s)
## example: 
campns.selected <- campns[c(10,100,80)] 


datUsing <- setkey(dat[.(campns.selected, ages.selected, dates)][!is.na(variable)], "variable")
totUsing <- setkey(tot[.(dates)][!is.na(variable)], "variable")


#  (5) Plot The Age Group & Campaign + Totals

key(dat)






G <- 
ggplot(data=datUsing[.(agg, TRUE)], aes(x=Date, y=value, color=Campaign)) + 
  geom_point(size=1) + geom_line(size=0.2) +  theme(legend.position="bottom")

ggplot() +
geom_point(data=totUsing[.(agg)], aes(x=Date, y=value), size=2, color="red") + 
      geom_line(data=totUsing[.(agg)], aes(x=Date, y=value), size=1.2, alpha=0.5) + 
      facet_grid(variable~.)

