Implicit in many statistical models is a function that takes the explanatory variables as inputs and returns the corresponding model value at those inputs. mod_fun creates an R function that works this way. The function returned by `mod_fun`` has arguments named for each of the explanatory variables. In calling that returned function, you can specify as many or as few of these as you like.

mod_fun(mod, nlevels = 1)

Arguments

mod

the model to be rendered in a functional form

nlevels

the number of levels for which to find "typical levels" for those arguments not specified in the call to the returned function

Value

a function whose arguments are the explanatory variable used in the model

Details

When you evaluate the function, you can set the values of all, any, or none of the arguments. Any arguments that you do not set will automatically be set to "typical values" as in mod_eval.

There's nothing essential about the behavior of `mod_eval`` that explicitly names the arguments to the model function with the names of the explanatory variables. This has been done purely for pedagogical reasons, as a reminder of what those variables are and to make it possible to spot mistaken inputs to models.

Examples

my_mod <- lm(mpg ~ hp * cyl, data = mtcars) f <- mod_fun(my_mod) names(formals(f)) # the arguments will be the explanatory variables
#> [1] "hp" "cyl"
f(hp = 1:2)
#> hp cyl model_output #> 1 1 6 25.98411 #> 2 2 6 25.93186
f(hp = 1:2, cyl = 3:4)
#> hp cyl model_output #> 1 1 3 38.28232 #> 2 2 3 38.17085 #> 3 1 4 34.18292 #> 4 2 4 34.09119
f() # typical values for inputs
#> hp cyl model_output #> 1 120 6 19.76569