I have a model with Machine
as factorial variable. The contrast is set to "contr.sum".
library(MEMSS)
#> Warning: package 'MEMSS' was built under R version 3.6.3
#> Loading required package: lme4
#> Loading required package: Matrix
#>
#> Attaching package: 'MEMSS'
#> The following objects are masked from 'package:datasets':
#>
#> CO2, Orange, Theoph
str(Machines)
#> 'data.frame': 54 obs. of 3 variables:
#> $ Worker : Factor w/ 6 levels "1","2","3","4",..: 1 1 1 2 2 2 3 3 3 4 ...
#> $ Machine: Factor w/ 3 levels "A","B","C": 1 1 1 1 1 1 1 1 1 1 ...
#> $ score : num 52 52.8 53.1 51.8 52.8 53.1 60 60.2 58.4 51.1 ...
fm <- lm(score ~ Machine, Machines, contrasts = list(Machine = "contr.sum"))
summary(fm)
#>
#> Call:
#> lm(formula = score ~ Machine, data = Machines, contrasts = list(Machine = "contr.sum"))
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -17.3222 -2.1431 0.4444 4.4403 9.3778
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 59.6500 0.7861 75.884 < 2e-16 ***
#> Machine1 -7.2944 1.1117 -6.562 2.68e-08 ***
#> Machine2 0.6722 1.1117 0.605 0.548
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 5.776 on 51 degrees of freedom
#> Multiple R-squared: 0.5077, Adjusted R-squared: 0.4884
#> F-statistic: 26.3 on 2 and 51 DF, p-value: 1.415e-08
How can I use the predict function to calculate the average over all machines? Just like I can do it for machine A:
pred_dat <- data.frame(Machine = "A")
predict(fm, newdata = pred_dat)
#> 1
#> 52.35556
This, of course, will not work. But it would be nice to have it that simple.
pred_dat <- data.frame(Machine = "mean_over_all_machines")
predict(fm, newdata = pred_dat)
#> Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels): factor Machine has new level mean_over_all_machines
The most obious way to get the mean over all levels is to just take the intercept, which is the mean. But I want to use the predict function with complex mixed models, many variables, interactions and random effects etc. (in this case glmmTMB). So, writing the complete term for the calculation of the average is not really an option.
For me this seems like a very general functionality and I am wondering why there is no option to predict without considering the categorical level.
tapply(Machines$score , Machines$machine ,mean)
$\endgroup$