force()
!Function Factories and Lazy Evaluation in R
force()
function
is created and will be called laterA function factory is a function that returns another function.
[1] 16
R uses lazy evaluation, meaning function arguments are not evaluated until needed.
[1] 10
[1] 11
force()
Use force()
to evaluate arguments immediately inside the factory.
The definition of force
is simple…
[1] 5
sub_populations <- c("a","b","c")
rates <- c(1, 0.5, 2)
rate_function_factory <- function(rate){
force(rate)
function() rate
}
rate_functions <- list()
for(i in seq_along(sub_populations)){
rate <- rates[i]
sub_population <- sub_populations[i]
rate_functions[[sub_population]] <- rate_function_factory(rate)
}
rate_functions[["a"]]()
boot_model <- function(df, formula) {
mod <- lm(formula, data = df)
fitted <- unname(fitted(mod))
resid <- unname(resid(mod))
rm(mod)
function() {
fitted + sample(resid)
}
}
boot_mtcars2 <- boot_model(mtcars, mpg ~ wt)
head(boot_mtcars2())
[1] 21.00000 21.00000 24.19270 19.07515 20.19749 18.59311
[1] 20.67161 21.86952 25.03800 18.21963 16.61753 19.99431
force()
to ensure the function has the correct bindingThe Dark Side of the
force()
is a pathway to many abilities some consider to be unnatural
For more info see Hadley Wickham’s Advanced R