0

I would like to count the nr of Sessions based on number of observation in the ID variable

Here are the variables

ID <- c(1,1,2,2,2,3,3,3,3)
Days <- c(0,5,0,5,10,0,5,10,15)
Sessions <- c(1,2,1,2,3,1,2,3,4)

Here are the data i have:

Have <- data.table(ID,Days)
Have
ID Days
1    0
1    5
2    0
2    5
2   10
3    0
3    5
3   10
3   15

Here are the data i whant to get:

Whant <- data.table(ID,Days,Sessions)
Whant
ID Days Sessions
1    0       1
1    5       2
2    0       1
2    5       2
2   10       3
3    0       1
3    5       2
3   10       3
3   15       4

Thank you so much if someone can help me with this. This is a great forum!

Carl
  • 111
  • 6

1 Answers1

0

We group by 'ID', and create the 'Sessions' as the sequence of rows (1:.N).

Have[, Sessions:= 1:.N, ID]

Or we can use a wrapper (getanID) from library(splitstackshape)

library(splitstackshape)
getanID(Have, 'ID')[]
akrun
  • 874,273
  • 37
  • 540
  • 662