I have a very long data frame (over 300 000 rows), consisting of all subjects trials of a task, in long format. So about 300 rows is successive trials for one subject, followed by the other subjects underneath. What I want to do is create a new column with trial numbers for every subject.

Such as:

subject trial_number 101 1 101 2 101 3 102 1 102 2 102 3

I am thinking I should somehow make R choose a subject number from column subject, and then create an ascending list and then loop this over all the subject numbers. But I have not been able to figure out how to loop over subject numbers, while also creating an ascending list in one and the same column over these subjects?

I don't have example code for failed attempts or so, as I haven't been able to figure out how to structure this. I'm thinking some kind of combination of subset and within? Or are there better solutions my googling skills haven't helped me find yet?


If I understand your question correctly, and assuming that your initial data frame looks something like trial_df below, you can use the following code and the dplyr package.


# create data frame 
trial_df <- tibble('subject' = c(rep('101', 3), rep('102', 3)),
                  'result' = c(32, 33, 64, 12, 18, 14))

# group by subject and add a row number
# assumes your data frame is ordered by trial number for each subject
new_df <- trial_df %>%
  group_by(subject) %>%
  mutate(trial_number = row_number())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.