title: Find first and last occurrence of an item in R dataframe
body: <p>I have a dataframe with <code>df</code> with two columns called <code>item</code> and <code>week</code>. This is how it looks like:</p>
  
  <pre><code> week           item
   1179           63230
   1179           63233
   1180           63230
   1180           63233
   1181           63230
   1181           63233
  </code></pre>
  
  <p>I would like to find the first and last <code>week</code> of occurrence of each <code>item</code> in the dataframe, and then compute the difference between last and end <code>week</code>. I tried to use the solution provided in this link - <a href="https://stackoverflow.com/questions/11546684/how-can-i-find-the-first-and-last-occurrences-of-an-element-in-a-data-frame">How can I find the first and last occurrences of an element in a data.frame?</a>. The code that I used is as follows:</p>
  
  <pre><code>df_start &lt;- df[!duplicated(df$item),]#Get starting week
  df_end &lt;- df[rev(!duplicated(rev(df$ITEM))),]#Get ending week
  </code></pre>
  
  <p>But, this does not give me the correct start and end <code>week</code>. Could someone help me out?</p>
  
  <p>I am also including an expected output. <code>df</code> has about 3 million rows, but the output for the above portion of <code>df</code> should be as follows:</p>
  
  <pre><code>&gt;df_start
  
  item     start_week
  63230     1179
  63233     1179
  
  &gt;df_end
  
  item      end_week
  63230       1181
  63233       1181
  </code></pre>