Q:

Using quantile function in data.table

I try to calculate the mean of some values in a data.table. The mean should be calculated without outliers, which means i have to filter the data first.
In order to define outliers in my data i use the "default boxplot" approach.
This approach works perfectly:
test <- template[Month==1] # create small subset with data from January
qnt <- quantile(test$x,c(.25,.75)
H <- 1.5 * IQR(test$x)
test[x < (qnt[2]+H) & x > (qnt[1]-H),mean(add)]
[1] -6113.136

I can also make the calculations within the datatable:
test <- template[Month==1] # create small subset with data from January
test[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)]
[1] -6113.136

Since i need the mean not only for January but for all months i tried this:
template[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x),by=Month]
 1:     1 -5601.3050 <<< not the same value than before
 2:     2  1187.3186
 ...

The January of the last approach is different than the January before. As far as i could figure out the quantile() method is the issue. I guess it doesn't include the 'by=Month' grouping of the data.table.
Is there anything wrong about my general approach?
Is there a way to make those calculations without splitting the 'template' data.table in 12 smaller tables first?
Many thanks for your help!
Update:
template[,.SD[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)],by=Month]
1:     1 -6113.1362
2:     2  1529.4808

Thanks @Frank and @Roland for the super fast support!

A:

template[,.SD[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)],by=Month]

as Frank and Roland stated out i needed to change my expression because i arg in DT[i,j,by] does not use the by grouping. Using .SD[] is the solution

