-1

I have a set of data from children, recorded across a number of sessions. The number of sessions and age of each child in each session is different for each participant, so it looks something like this:

 library(tibble)
 mydf <- tribble(~subj, ~age,
            "A", 16,
            "A", 17, 
            "A", 19,
            "B", 10,
            "B", 11,
            "B", 12,
            "B", 13)

What I don't currently have in the data is a variable for Session number, and I'd like to add this to my dataframe. Basically I want to create a numeric variable that is ordinal from 1-n for each child, something like this:

 mydf2 <- tribble(~subj, ~age, ~session,
            "A", 16, 1, 
            "A", 17, 2,
            "A", 19, 3,
            "B", 10, 1,
            "B", 11, 2,
            "B", 12, 3
            "B", 13, 4)

Ideally I'd like to do this in dplyr().

Catherine Laing
  • 475
  • 6
  • 18

1 Answers1

1

You simply need to group by subj and use row_number():

mydf %>% 
  group_by(subj) %>% 
  mutate(session = row_number())
jon
  • 370
  • 1
  • 11