Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pasting values from a vector to a new column in a for loop with nested data

I have a dataframe that currently looks like this:

subjectID Trial
1 3
1 3
1 3
1 4
1 4
1 5
1 5
1 5
2 1
2 1
2 3
2 3
2 3
2 5
2 5
2 6
3 1

Etc., where trial number is nested under subject ID. I need to make a new column in which column "NewTrial" is simply what order the trials now appear in. For example:

subjectID Trial NewTrial
1 3 1
1 3 1
1 3 1
1 4 2
1 4 2
1 5 3
1 5 3
1 5 3
2 1 1
2 1 1
2 3 2
2 3 2
2 3 2
2 5 3
2 5 3
2 6 4
3 1 1

So far, I have a for-loop written that looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (myperson in unique(data$subjectID)){

#This line creates a vector of the number of unique trials per subject: for subject 1, c(1, 2, 3)
triallength=1:length(unique(data$Trial[data$subID==myperson]))

I’m having trouble now finding a way to paste the numbers from the created triallength vector as a column in the dataframe. Does anyone know of a way to accomplish this? I am lacking some experience with for-loops and hoping to gain more. If anyone has a tidyverse/dplyr solution, however, I am open to that as well as an alternative to a for-loop. Thanks in advance, and let me know if any clarification is needed!

>Solution :

We could use match on the unique values after grouping by ‘subjectID’

library(dplyr)
df1 <- df1 %>% 
  group_by(subjectID) %>%
  mutate(NewTrial = match(Trial, unique(Trial))) %>%
  ungroup
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading