title: Get first and last values per group – dplyr group_by with last() and first()
body: <p>The code below should group the data by year and then create two new columns with the first and last value of each year.</p>
  
  <pre><code>library(dplyr)
  
  set.seed(123)
  
  d &lt;- data.frame(
      group = rep(1:3, each = 3),
      year = rep(seq(2000,2002,1),3),
      value = sample(1:9, r = T))
  
  d %&gt;% 
      group_by(group) %&gt;%
      mutate(
          first = dplyr::first(value),
          last = dplyr::last(value)
      )
  </code></pre>
  
  <p>However, it does not work as it should. The expected result would be</p>
  
  <pre><code>  group  year value first  last
    &lt;int&gt; &lt;dbl&gt; &lt;int&gt; &lt;int&gt; &lt;int&gt;
  1     1  2000     3     3     4
  2     1  2001     8     3     4
  3     1  2002     4     3     4
  4     2  2000     8     8     1
  5     2  2001     9     8     1
  6     2  2002     1     8     1
  7     3  2000     5     5     5
  8     3  2001     9     5     5
  9     3  2002     5     5     5
  </code></pre>
  
  <p>Yet, I get this (it takes the first and the last value over the entire data frame, not just the groups):</p>
  
  <pre><code>  group  year value first  last
    &lt;int&gt; &lt;dbl&gt; &lt;int&gt; &lt;int&gt; &lt;int&gt;
  1     1  2000     3     3     5
  2     1  2001     8     3     5
  3     1  2002     4     3     5
  4     2  2000     8     3     5
  5     2  2001     9     3     5
  6     2  2002     1     3     5
  7     3  2000     5     3     5
  8     3  2001     9     3     5
  9     3  2002     5     3     5
  </code></pre>