I am trying to compute predictions using the R::marginaleffects package. I would like to do this several times for specific predictor variables of interest, within a map / apply like function, but am struggling to get the syntax right. My attempt is:
pred_list <- map(list("var1 = 1:10", "var2=21:30"), \(x) predictions(my_model, newdata = datagrid(!!x)))
However, this does not give me a list of predictions for each of var1 and var2, across the specified ranges, with other predictors in the model held at default values.
Any help would be much appreciated.
You can use do.call()
to feed arguments to the datagrid()
function. Note that you need to specify the model object explicitly because of scoping issues:
library(marginaleffects)
mod <- lm(mpg ~ hp + wt, data = mtcars)
args <- list(list(wt = 1:3, model = mod), list(hp=100:103, model = mod))
lapply(args, function(x) predictions(mod, newdata = do.call(datagrid, x)))
> [[1]]
>
> wt Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 % hp
> 1 28.7 1.476 19.4 <0.001 277.2 25.8 31.6 147
> 2 24.8 0.896 27.7 <0.001 557.8 23.1 26.6 147
> 3 20.9 0.479 43.7 <0.001 Inf 20.0 21.9 147
>
> Columns: rowid, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, hp, wt, mpg
> Type: response
>
>
> [[2]]
>
> hp Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 % wt
> 100 21.6 0.623 34.6 <0.001 871.0 20.4 22.8 3.22
> 101 21.5 0.617 34.9 <0.001 885.5 20.3 22.8 3.22
> 102 21.5 0.611 35.2 <0.001 900.3 20.3 22.7 3.22
> 103 21.5 0.605 35.5 <0.001 915.2 20.3 22.7 3.22
>
> Columns: rowid, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, wt, hp, mpg
> Type: response