rmodelr

Create multiple formulas with formulas() inside map()


I need to create several formulas with modelr::formulas() function that differentiate with respect to some independent variables for each group I have. For example, I would like to generate, for Group 1 and Group 2

log(price) ~ year + 'var1_Group 1':var2
log(price) ~ year + 'var1_Group 1':var3

log(price) ~ year + 'var1_Group 2':var2
log(price) ~ year + 'var1_Group 2':var3

I tried without success use as.formula() function:

 map(c("Group 1", "Group 2"),
  
  .f = \(x) {
    
    formulas <- formulas(~ log(price),
                         reg1 = as.formula(~ year + str_c("`var1_", x, "`:var2")),
                         reg2 = as.formula(~ year + str_c("`var1_", x, "`:var3")))
    
  })

Which returns to me:

[[1]]
[[1]]$reg1
log(price) ~ year + str_c("`var1_", x, "`:var2")
<environment: 0x0000027365340dc0>

[[1]]$reg2
log(price) ~ year + str_c("`var1_", x, "`:var3")
<environment: 0x0000027365340dc0>


[[2]]
[[2]]$reg1
log(price) ~ year + str_c("`var1_", x, "`:var2")
<environment: 0x000002730bac4590>

[[2]]$reg2
log(price) ~ year + str_c("`var1_", x, "`:var3")
<environment: 0x000002730bac4590>

Thanks in advance!


Solution

  • Using sprintf and outer before as.formula.

    > f <- \(x, y) sprintf("log(price) ~ year + `var1_%s`:%s", x, y)
    > outer(c('Group 1', 'Group 2'), c('var2', 'var3'), f) |> lapply(as.formula)
    [[1]]
    log(price) ~ year + `var1_Group 1`:var2
    <environment: 0x61d285e1b4d8>
    
    [[2]]
    log(price) ~ year + `var1_Group 2`:var2
    <environment: 0x61d285e1b4d8>
    
    [[3]]
    log(price) ~ year + `var1_Group 1`:var3
    <environment: 0x61d285e1b4d8>
    
    [[4]]
    log(price) ~ year + `var1_Group 2`:var3
    <environment: 0x61d285e1b4d8>
    

    Think of outer as a cross-product Map, similar to a nested for-loop.