Is there a robust way to programmatically create non-standard formulas? I know about reformulate
but that doesn't handle random effects specifications, etc. I want to do something like the following:
library(lme4)
outcome <- "Sepal.Width"
fixed_effects <- c("Species", "Petal.Width")
random_intercepts <- c("Sepal.Length", "Petal.Length")
randomify <- function(feats) paste0("(1|", feats, ")", collapse = " + ")
fixed <- paste0(fixed_effects, collapse = " + ")
random <- randomify(random_intercepts)
formula <- as.formula(paste(outcome, "~", fixed, "+", random))
lmer(formula, iris)
#> Linear mixed model fit by REML ['lmerMod']
#> Formula: Sepal.Width ~ Species + Petal.Width + (1 | Sepal.Length) + (1 |
#> Petal.Length)
#> Data: iris
#> REML criterion at convergence: 76.0282
#> Random effects:
#> Groups Name Std.Dev.
#> Petal.Length (Intercept) 0.04213
#> Sepal.Length (Intercept) 0.08105
#> Residual 0.28806
#> Number of obs: 150, groups: Petal.Length, 43; Sepal.Length, 35
#> Fixed Effects:
#> (Intercept) Speciesversicolor Speciesvirginica
#> 3.2558 -1.5048 -1.8273
#> Petal.Width
#> 0.7613