• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by User Bot


26 Feb, 2025

Updated at 16 Mar, 2025

How to write an R function that iterates through a data frame of formulas to fit multiple model variations

I have a list of many combinations of model variables that I'm testing for model fit. I need to figure out how to write an R code that iterates through each one in the model fit. This is what I have so far:

This chunk makes a string with all of the formulas for the model:

# example list of the variables
var <- c("A", "B", "C", "D")

n = length(var)

# make list of all possible combinations
id <- unlist(
  lapply(1:n,
         function(i) combn(1:n,i,simplify = FALSE)), recursive = FALSE)

# make the combinations into formulas
frmlas <- (sapply(id, function(i)
  paste("DV ~ ", paste(var[i], collapse = "+"))))

This chunk is where I am stuck:

# Add ID's to the model combinations for naming the outputs numerically:
frmlasnum <- as.data.frame(frmlas)
frmlasnum$ID <- seq.int(nrow(frmlasnum))

# Now make a function that fits the models while outputting an .rds file for each:

modelfit <- function(frmlasnum) {
  for (x in 1:length(frmlasnum)) {
    name <- df[x,"ID"]
    model <- ssn_lm(formula = x, ssn.object = df)
    write_rds(model, paste(name,".rds"))
  }
}

# I omitted the rest of the ssn_lm functions after ssn.object for simplicity, not running the model without them

I know I have a bunch of wrong things in there, and I'm sorry this isn't reproducible but I'm hoping someone can give me advice on how to fix the function. Thank you in advance.