title: R Use map2 to iterate over columns within a list of data frames to fit statistical models
body: <p>I'm trying to figure out a purrr approach to iteratively map over columns within a list of data frames to fit univariate GLMs. Using <code>map2</code>, the first element, <code>.x</code>, would be the three pred columns, and the second element, <code>.y</code>, would be the list of data frames (or vice-versa). <code>map2</code> seems to be able to do this, but I recognize that I need to cross the .x and .y elements first, so I use <code>tidyr::crossing</code> first to do this. From here, I am unsure how to properly reference the columns to select within the data frames. Example code is below:</p>
  
  <pre><code>#Sample data
  set.seed(100)
  test_df &lt;- tibble(pred1 = sample(40:80, size = 1000, replace = TRUE),
                    pred2 = sample(40:80, size = 1000, replace = TRUE),
                    pred3 = sample(40:80, size = 1000, replace = TRUE),
                    resp = sample(100:200, size = 1000, replace = TRUE),
                    group = sample(c('a','b','c'), size = 1000, replace = TRUE))
  
  #Split into list
  test_ls &lt;- test_df %&gt;% 
    group_by(group) %&gt;% 
    {df_groups &lt;&lt;- .} %&gt;% 
    group_split()
  
  #Obtain keys and name list elements
  group_keys &lt;- df_groups %&gt;% 
    group_keys() %&gt;% 
    pull()
  
  test_ls &lt;- test_ls %&gt;% setNames(nm = group_keys)
  
  #Cross all combinations of pred columns and list element names
  preds &lt;- c('pred1','pred2','pred3')
  map_keys &lt;- crossing(preds, group_keys) 
  
  #.y = list of data frames; iterate over data frames
  #.x = three pred columns; iterate over columns
  #Use purrr to fit glm of each .x columns within each of .y dfs
  
  #Example structure - does not work
  map2(.x, .y, .f = ~glm(resp ~ .x, data = .y))
  
  #Workaround that does work
  lapply(test_ls, function(x) {
    x %&gt;% 
      select(pred1, pred2, pred3) %&gt;% 
      map(.f = ~glm(resp ~ .x, data = x))
  })
  </code></pre>
  
  <p>There's something I'm missing, and I can't seem to figure it out. I've gotten a variety of errors with a few approaches, but I think it's coming down to not properly referencing the <code>.x</code> columns within the <code>.y</code> data frames. My approaches don't seem to recognize that <code>.x</code> is a column within <code>.y</code>. The workaround does the trick, but I'd prefer to avoid using both <code>lapply</code> and <code>map</code>.</p>