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?
Asked
Active
Viewed 56 times
-1
-
2`df %>% group_by(subject) %>% mutate(trail = row_number())` ? – Ronak Shah Jun 27 '20 at 12:50
-
@RonakShah Error: `n()` must only be used inside dplyr verbs. – amarykya_ishtmella Jun 27 '20 at 13:14
1 Answers
1
Here is another alternative with data.table
package. 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