Q:

Pass a dynamic value to aggregate function in R

I am trying to aggregate Profit based on either Year, Month or Date level. I am reading the level of aggregation from another file and want to pass it to the aggregate function the values from that file, but it is throwing an error.
library(lubridate)

parameter <- read.csv("Parameter.csv",header = F,col.names = c("Option","Value"))
head(parameter)
orders <- read.csv("Orders_Data.csv")
str(orders)

orders$Order.Date <- as.POSIXct(orders$Order.Date,format ="%m/%d/%Y")
orders$month = months(orders$Order.Date)
orders$Year <- year(orders$Order.Date)
head(orders$Year)

option = as.character(parameter[1,2]) #option holds the level of aggregate
option

#[1] "Day"

aggregate(Profit ~ Category + option ,data = orders, sum)

Error is
Error in model.frame.default(formula = Profit ~ Category + option, data = orders) : 
  variable lengths differ (found for 'option')

Here is reproducible data
option = "Year"

aggregate(Profit ~ Category + option ,data = orders, sum)

example = data.frame(date = sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 24)
                    ,Profit =  sample(seq(-200,1200),24)
                    , Department = sample(LETTERS[seq( from = 1, to = 26 )],24))   

example$Year <- year(example$date)
head(example)
aggregate(Profit ~ Department + option,data = example, sum)

Still the same error

A:

In short, you would need to manually create a string formula, then transform it to an actual formula, and then pass it to aggregate.
Like this:
option="Year"
formula=as.formula(paste0("Profit ~ Department + ",option))
aggregate(formula,data = example, sum)

However, i feel using data.table would be much easier (and quicker!):
library(data.table)
example=data.table(example)

example[,.(Profit=sum(Profit)),by=c("Department",option)]

