title: dplyr and tidyr - calculating a lot of linear models at once with factors
body: <p>After reading more into the tidyverse, I started fitting many linear models at once as described in <a href="https://blog.rstudio.org/2016/02/02/tidyr-0-4-0/" rel="nofollow">this</a>. Namely, I would do something along these lines:</p>
  
  <pre><code>library(dplyr)
  library(tidyr)
  library(purrr)
  df &lt;- data.frame(y = rnorm(10), 
                   x1 = runif(10),
                   x2 = runif(10))
  
  df %&gt;%
    gather(covariate, value, x1:x2) %&gt;% 
    group_by(covariate) %&gt;% 
    nest() %&gt;% 
    mutate(model = map(.x = data , .f = ~lm(y ~ value, data = .))) %&gt;% 
    mutate(rsquared = map_dbl(.x = model, .f = ~summary(.)$r.squared))
  </code></pre>
  
  <p>The problem is that this approach fails when the variables are not of the same type, for example when one is numeric and one is a factor, as the <code>gather()</code> function will coerce the whole <code>value</code> vector into a factor. For example,</p>
  
  <pre><code>df &lt;- data.frame(y = rnorm(10), 
                   x1 = runif(10),
                   x3 = sample(c("a", "b", "c"), 10, replace = TRUE))
  
  df %&gt;%
    gather(covariate, value, x1:x3) %&gt;% 
    sapply(class)
  </code></pre>
  
  <p>is followed by the warning</p>
  
  <pre><code>Warning message:
  attributes are not identical across measure variables; they will be dropped 
  
            y   covariate       value 
    "numeric" "character" "character" 
  </code></pre>
  
  <p>and the <code>value</code> column is a character, so the trick with <code>nest()</code> will not work any more as all the covariates will be put in as factors.</p>
  
  <p>I am wondering whether there is a <em>tidy</em> way of doing this. </p>