Reputation: 1847
Is there a way how to iterate over formula in R?
what I need to do lets say we have a formula given as: as.formula(hp ~ factor(gear) + qsec + am)
What I need to do is to iterate over elements of formula So I can create 3 model (3 because we use 3 regressors - no counting dummies)
I need to create first model as as.formula(hp ~ factor(gear))
, then second like as.formula(hp ~ factor(gear) + qsec)
and lastly as.formula(hp ~ factor(gear) + qsec + am)
Can we somehow use just one regressor in one iterration, then use two and when use three?
I need to automatize this for function and "hand" approach is not good
Upvotes: 0
Views: 281
Reputation: 1624
My approach here: create a string using sprintf
and paste
(with collapse
option), coerce it to a formula, and then loop over the elements you want to include.
elements <- c("factor(gear)", "qsec", "am")
for (i in 1:length(elements)) {
fmla <- as.formula(sprintf("hp ~ %s", paste(elements[1:i], collapse = " + ")))
print(fmla)
print(summary(lm(fmla, data = mtcars)))
}
If you need to parse the formula gave, you could do something like this before running the loop above (might need to be modified for your specific setup):
library(stringr)
input_fmla <- "as.formula(hp ~ factor(gear) + qsec + am)"
temp <- str_remove_all(input_fmla, "(as.formula\\([^ ]* ~ |\\)$)")
elements <- trimws(str_split(temp, pattern = "\\+")[[1]])
Upvotes: 1