title: How to index in a column based on the unique values in another column
body: <p>I have a dataset DF, which includes two columns of USER and DATETIME (column index is not in my data. It is what the output should look like). The rows in DF shows the activity in each minute. What I want is to create and fill a column called “index”. This index is to show the activities of equal to or less than 4 minutes. In other words, if the difference between DATETIME of row i and its following row i+1 is less than or equal to 4 minutes, they are in the same index (namely, in the same activity). But, if this difference is greater than 4 minutes, the next row (i+1) goes to the next activity and so on. Here is important. <strong>I do not need</strong> a code for the difference between DATETIMES. I have it here. What I want is a for loop that indexes the activities for each unique USER. Then, for the next USER, it should start from 1.  This is what I have tried. But I need a for in for loop or unique function. The output should look like the column “index”. Thanks for your help.</p>
  
  <p><a href="https://i.stack.imgur.com/ejHtR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ejHtR.png" alt="enter image description here"></a></p>
  
  <pre><code>suum &lt;- 1
  DF$index[1] &lt;- 1 
  
  for (k in unique(DF$USER))
  
     {
  
    for (i in 2:(nrow(DF)))
     {
     if(as.numeric(difftime(ymd_hms(DF$DATETIME[i]), ymd_hms(DF$DATETIME[i-1]), units = "mins") &lt;= 4)) 
        { DF$index[i] &lt;- suum }
  
   else if(as.numeric(difftime(ymd_hms(DF$DATETIME[i]), ymd_hms(DF$DATETIME[i-1]),units = "mins") &gt; 4))
      {DF$index[i] &lt;- suum + 1}
      suum &lt;- as.numeric(DF$index[i])
      } 
  
        }  
  </code></pre>
  
  <p>Thanks to @Paul van Oppen for bringing my data in the format of R</p>
  
  <pre><code>data &lt;- tibble(USER = c(rep(41, 10), rep(61, 6)),
  DATETIME = as.POSIXct(c("2019/06/02 20:44:00", # 41
                        "2019/06/03 16:46:00", 
                        "2019/06/03 16:50:00", 
                        "2019/06/03 20:43:00", 
                        "2019/06/03 20:44:00", 
                        "2019/06/03 21:45:00", 
                        "2019/06/03 21:47:00", 
                        "2019/06/04 13:29:00", 
                        "2019/06/04 13:30:00",
                        "2019/06/04 13:37:00",
                        "2019/06/02 10:34:00", # 61
                        "2019/06/02 11:41:00",
                        "2019/06/02 11:59:00",
                        "2019/06/02 12:00:00",
                        "2019/06/02 14:12:00",
                        "2019/06/02 14:13:00"), 
                          "%Y/%m/%d %H:%M:%S", tz = "UTC")
  
                               )
  </code></pre>