title: Using group_by() from dplyr with predict.lm and do() in a pipe for year linear extrapolation
body: <p>I would like to apply a linear extrapolation for one year within a pipe. What I would like to do is very similar to this <a href="https://stackoverflow.com/questions/8352673/doing-linear-prediction-with-r-how-to-access-the-predicted-parameters">simple example without grouping</a>. But within a pipe and employing <code>dplyr::group_by()</code>. There are some examples <a href="https://stackoverflow.com/questions/32773617/add-column-of-predicted-values-to-data-frame-with-dplyr">like this one</a>, <a href="https://stackoverflow.com/questions/29140530/showing-fitted-values-with-r-and-dplyr/29142831#29142831">this one</a> or <a href="https://stackoverflow.com/questions/29140530/showing-fitted-values-with-r-and-dplyr/29142831#29142831">this one</a>. But I can't manage to get the desirable output.</p>
  <p>Reproducible example:</p>
  <pre><code>test.frame &lt;- data.frame(Country = 
  rep(c(&quot;Austria&quot;, &quot;Brazil&quot;, &quot;Canada&quot;), each = 3, times = 3), 
    Entity = rep(c(&quot;CO2&quot;,&quot;CH4&quot;,&quot;N2O&quot;), times = 9),
    Year = rep(c(1990:1992), each = 9),
    value = runif(27, 1,5))
  
  test.frame2 &lt;- data.frame(Country = 
  rep(c(&quot;Austria&quot;, &quot;Brazil&quot;, &quot;Canada&quot;), each = 3), 
      Entity =  rep(c(&quot;CO2&quot;,&quot;CH4&quot;,&quot;N2O&quot;), times = 3),
      Year = rep(c(1993), each = 3),
      value = 0)
  
  results_frame &lt;- test.frame %&gt;% 
    dplyr::bind_rows(test.frame2)
  </code></pre>
  <p>I have two grouping categories (Country and Entity), and I would like to use the values for years 1990 to 1992 to fill those for year 1993 using linear extrapolation.
  On the basis of <a href="https://stackoverflow.com/questions/8352673/doing-linear-prediction-with-r-how-to-access-the-predicted-parameters">this</a>, I can estimate the linear model:</p>
  <pre><code>linear_model &lt;- test.frame %&gt;%  
  dplyr::group_by(Country, Entity) %&gt;% 
  lm(value ~ Year, data=.)
  
  results &lt;- predict.lm(linear_model, test.frame2)
  </code></pre>
  <p>But then, <code>results</code> doesn't show the desirable output. So following the solution proposed <a href="https://stackoverflow.com/questions/32773617/add-column-of-predicted-values-to-data-frame-with-dplyr">here</a> I try the following:</p>
  <pre><code>results_frame &lt;- test.frame %&gt;%
    dplyr::group_by(Country, Entity) %&gt;% 
    do(lm( value ~ Year , data = test.frame)) %&gt;%
    predict.lm(linear_model, test.frame2) %&gt;% 
    bind_rows(test.frame)
  </code></pre>
  <p>But it doesn't work, instead I get</p>
  <blockquote>
  <p>Error: Results 1, 2, 3, 4, 5, ... must be data frames, not lm</p>
  </blockquote>
  <p>Any help would be highly appreciated!</p>