Modeling

I would like to loop over several outcomes in separate models as below:


 

# Loop through column names from 10 to 56
for (col in names(df)[10:57]) {
  # Create the formula dynamically
  formula <- paste0("bf(", col, " ~ X, sigma ~ X)")
  
  # Fit Bayesian regression model
  model <- brm(formula,
               data = df,
               prior = c(prior("normal(0, 50)", class = "Intercept"),
                         prior("normal(0, 50)", class = "sd"),
                         prior("normal(0, 50)", class = "b")),
               seed = 1, chains = 8, iter = 10000,
               control = list(adapt_delta = 0.99, max_treedepth = 13),
               cores = future::availableCores())
  
  # Save model
  save(model, file = paste0(col, "_Xsigma.RDATA"))
  }

however, I receive error as

 Error in class(ff) <- "formula" : attempt to set an attribute on NULL

I appreciate any guidance. Thanks

You have bf() inside the string generated by pasting the two formulas together and paste0 doesn’t know bf() is a function to be applied to the formulas. Try putting the string inside bf() instead: bf(paste0(col, " ~ X"), sigma ~ X). (There is also an issue with how the prior for the distributional parameter (dpar) sigma is specified.)

2 Likes

@desislava Thanks for the hint. It worked.