I'm currently working on a project combining machine learning and causal inference in R using caret. My dataset contains a variable that assigns the observations into certain groups. When training the ML models and predicting I'd like to mimic the behavior of a fixed effect estimator by removing the mean of each variable by the specific group.
For example my data may look like this:
DT <- data.table(a = seq(1, 100),
b = seq(101, 200),
c = seq(201, 300),
group = rep(seq(1,10), 10))
I know that I can use the caret's built-in "center" method in the train() function for preProcessing. However, I need to apply this preprocessing step, not over the complete data set, but over each level of the "group" variable separately.
Is there an easy way to implement this behavior, i.e. calculating grouped means on the training set and use these same means to apply the centering preprocessing when predicting on a separate test set, using caret?
Any help would be highly appreciated, thank you.