title: R data.table finding min and max within groups
body: <p>Hi I have this problem where I have a dataset where a person works in different companies. Now I want to find the duration of each company he worked for. Some person goes back to his previous company to work. Here is my dataset and my implementation, but it doesn't work when he goes back to his previous company later.</p>
  <pre><code>library(data.table)
  data &lt;- data.table(person = c(1,1,1,1,1,1,1,1), company = c(1,1,1,2,2,2,1,1),
                 year = c(1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997))
  </code></pre>
  <p>You see person == 1 works in company 1 from 1990 to 1992 and then switched to company 2 from 1993 to 1995. Then he goes back to company 1 from 1996 to 1997.</p>
  <p>I thought about using</p>
  <pre><code>min &lt;- data[data[, .I[year == min(year)], by=.(person, company)]$V1]
  setnames(min, &quot;year&quot;, &quot;start&quot;)
  
  max &lt;- data[data[, .I[year == max(year)], by=.(person, company)]$V1]
  setnames(max, &quot;year&quot;, &quot;end&quot;)
  
  duration &lt;- merge(min, max, all = T)
  </code></pre>
  <p>which you get:</p>
  <pre><code>person company start  end
       1       1  1990 1997
       1       2  1993 1995
  </code></pre>
  <p>But what I want is:</p>
  <pre><code>person company start  end
       1       1  1990 1992
       1       2  1993 1995
       1       1  1996 1997
  </code></pre>
  <p>Any idea how to get that?</p>
  <p>Thanks.</p>