title: annotate grouped linear models with dplyr, broom, and ggplot
body: <p>I am starting to delve into broom to visualize simple statistical analysis in dplyr/ggplot. I worked out how to get linear models by grouping to work well using by tying in broom::augment.</p>
  <p>I have three questions:</p>
  <ol>
  <li>What is the elegant way to tie in the summary information of the fits (r squared, intercept, p vals) by group back to the original dataframe (in this case all values in the group would be identical)?</li>
  <li>How could one annotate the regression lines for each group with just a single value to display the r squared and maybe curve fit) in the plot? In particular, how would one get the alignment/color right so that it's clear which text annotation goes with which regression line?</li>
  <li>After I sorted out how to do the grouped analysis based on some older SO answers, I learned that the <code>do</code> is now superseded by <code>across()</code>, but I am having a hard time figuring out how to rewrite <code>do(fit_carb = augment(lm(drat ~ mpg, data = .)))</code> using <code>across()</code>?</li>
  </ol>
  <pre><code>#// library and data prep
  library(tidyverse)
  library(broom)
  
  data &lt;- mtcars
  data$carb &lt;- as.factor(data$carb)
  
  #// generate scatter plot
  plot &lt;- 
       ggplot() + 
       geom_point(data = data, aes(x = mpg, y = drat, color = carb)) 
  
  #// use lm function to generate linear regression model
  fit &lt;- lm(formula = drat ~ mpg, data = data)
  
  #// tie results back into dataframe
  lm_data &lt;- augment(fit)
  
  #// add fitted points and line
  plot +    
       ggtitle(&quot;scatter plot with fitted points and line&quot;) + 
       #// add geom_point and geom_line with lm_data
       geom_point(data = lm_data, aes(x = mpg, y = .fitted), color = &quot;red&quot;) +
       geom_line(data = lm_data, aes(x = mpg, y = .fitted), color = &quot;red&quot;)
  
  
  #// linear model by group
  
  lm_data &lt;- data %&gt;%
       #// group by factor
       group_by(carb) %&gt;%
       #// `.` notation means that object gets piped into that place
       do(fit_carb = augment(lm(drat ~ mpg, data = .))) %&gt;% 
       #// unnest table by the augment results
       unnest(fit_carb)
  
  #// add fitted points and line grouped by carb
  plot +    
       ggtitle(&quot;scatter plot with fitted points and line&quot;) + 
       #// add geom_point and geom_line with lm_data
       geom_point(data = lm_data, aes(x = mpg, y = .fitted, group = carb), color = &quot;red&quot;) +
       geom_line(data = lm_data, aes(x = mpg, y = .fitted, group = carb, color = carb))
  </code></pre>
  <p><a href="https://i.stack.imgur.com/WEjqF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WEjqF.png" alt="ungrouped" /></a></p>
  <p><a href="https://i.stack.imgur.com/zIQg0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zIQg0.png" alt="grouped" /></a></p>