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

Create a column that increments for each unique ID in R

I have a dataset that looks something like this:

ID     Minutes Read    Comprehension     
1      25              1      
1      30              1      
2      20              2      
2      25              2     
2      30              1        

I want to create a column called "day" that counts the days each person reported reading, such as below:

ID     Minutes Read    Comprehension     Day  
1      25              1                 1
1      30              1                 2
2      20              2                 1
2      25              2                 2
2      30              1                 3

How would I go about doing that? The end goal is to use the "day" column to reshape my data,

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

df2 <- reshape(df, idvar="ID", timevar = "day", direction="wide").

>Solution :

Since your aim is to reshape the data, try:

reshape(transform(df, time = ave(ID, ID, FUN = seq)), dir = 'wide', idvar = 'ID')

  ID Minutes.Read.1 Comprehension.1 Minutes.Read.2 Comprehension.2 Minutes.Read.3 Comprehension.3
1  1             25               1             30               1             NA              NA
3  2             20               2             25               2             30               1

If you are only interested in the day column, then

df <- transform(df, day = ave(ID, ID, FUN = seq))
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