Dynamically entering formulas into complex multivariate model

I am specifying a complex multivariate model (using this tutorial: https://cran.r-project.org/web/packages/brms/vignettes/brms_multivariate.html). I have computed all the formulas required for the model and saved them as items in list m1. Now I combine them in the model like this:

fit1 <- brm(m1[1][[1]]+m1[2][[1]]+m1[3][[1]]+m1[4][[1]], data=df,iter=niter,chains=4,cores=4,family="gaussian",control=list(adapt_delta=0.9))

This works great, but the problem is that I would like to do a number of multivariate models in a loop. For this I need to dynamically enter the formulas because each multivariate model has a variable number of formulas. However I can’t find a way to do this - I have tried printing the formula references into strings:

printedm1 <- purrr::map_chr(c(1:length(m1)),function(x) {if (x==length(m1)){paste0('m1[',x,'][[1]]')

and then entered the formula references into the model like this:

fit1 <- brm(cat(sapply(printedm1,function(x) paste0(x)),sep=''), data=df,iter=niter,chains=4,cores=4,family="gaussian",control=list(adapt_delta=0.9))

but I receive the error Error in rhs(x)[[2]] : subscript out of bounds. Is there a way to enter the formula references dynamically? Thanks I appreciate any advice.

Hi,
generally creating formulas as strings and converting them to formulas should work.

However, if I get it correctly, the elements of m1 are already univariate formulas of class brmsformula, right? So here, m1[1][[1]]+m1[2][[1]]+m1[3][[1]]+m1[4][[1]] is not a formula (in R), that would be evaluated later. It is literally the result of applying the + to a set of brmsformula objects (this operator is defined in brms). So in this case, you should be able to work without strings, i.e. something like:

f_combinded <- m1[1][[1]]
if(length(m1) > 1) {
  for(i in 2:length(m1)) {
    f_combined <- f_combined + m1[i][[1]]
  }
}

brm(f_combined , ....)

should work (but I didn’t test it, so hope I am not wrong).

Thank you for this clever solution @martinmodrak! Looks like my problem was trying to combine the formulas using strings, when the formulas simply need to be added. Much appreciated.