0

I am a bit confused. I have a datatable similar to that:

library(data.table)
DT<-data.table(contract=c("c","c","c","d","d","d","d","f","f","f","f"),events=c("a","b","c","a","b","b","c","a","b","c","d"))


contract events
  c       a
  c       b
  c       c
  d       a
  d       b
  d       b
  d       c
  f       a
  f       b
  f       c
  f       d

And I would like to count the number of events by contract by keeping track of repetitions, so to end up with something like that:

contract events seqevents
      c       a       1
      c       b       2
      c       c       3
      d       a       1
      d       b       2
      d       b       2
      d       c       3
      f       a       1
      f       b       2
      f       c       3
      f       d       4

As a start, I tried to obtain a simple count of events by contract with this code, and then try to figure out a way to account for repetitions of the same event:

DT<-DT[ , seqevents := 1:.N , by = c("contract","events") ]

But the output is not correct, though it worked on a different data set. Any suggestions on why it doesn't work and how can I get a count as illustrated above? Thanks a lot

Frank
  • 66,179
  • 8
  • 96
  • 180

0 Answers0