Map-reduce example
Function that will return an expression corresponding to a linear model.
linear <- function(var, val) {
# capture variable as a symbol
var <- ensym(var)
# Create a list of symbols of the form var[[1]], var[[2], etc]
coef_name <- map(seq_along(val[-1]), ~ expr((!!var)[[!!.x]]))
# map over the coefficients and the names to create the terms
summands <- map2(val[-1], coef_name, ~ expr((!!.x * !!.y)))
# Dont forget the intercept
summands <- c(val[[1]], summands)
# Reduce!
reduce(summands, ~ expr(!!.x + !!.y))
}
linear(x, c(10, 5, -4))
#> 10 + (5 * x[[1L]]) + (-4 * x[[2L]])
#> 10 + (5 * x[[1L]]) + (-4 * x[[2L]])