-1

In my data frame on how to count the number of each subject id and add a trails column with those many numbers per subject. Say, I have sub 1 doing something 10 times so I want the trail as (1,2,3....10) and say sub2 is doing something 15 times(1,2,3,4...15).How can I do this?

1 Answers1

1

Here is another alternative with data.tablepackage. The code and the output is as follows:-

library(data.table)
df <- data.frame(subject = c("maths","maths","maths","science","science"))
df <- data.table(df)
df[, trail := seq_len(.N), by = subject]
df

#subject trail
#1:   maths     1
#2:   maths     2
#3:   maths     3
#4: science     1
#5: science     2
Sri Sreshtan
  • 535
  • 3
  • 12