I’m working with a dataset where a number of subjects had follow-up examinations over a period of time. The age at every examination is recorded:
subject <- c("subject1", "subject1", "subject2", "subject2", "subject2", "subject3", "subject3")
ageAtExam <- c(50, 51, 30, 32, 35, 40, 45)
df <- data.frame(subject, ageAtExam)
> df
subject ageAtExam
1 subject1 50
2 subject1 51
3 subject2 30
4 subject2 32
5 subject2 35
6 subject3 40
7 subject3 45
I’d like to create a new column where the age at the first examination (i.e. the minimum value in ageAtExam for every subject) is given:
subject ageAtExam ageAtFirstExam
1 subject1 50 50
2 subject1 51 50
3 subject2 30 30
4 subject2 32 30
5 subject2 35 30
6 subject3 40 40
7 subject3 45 40
I’m grateful for any suggestions, thanks!
>Solution :
Using ave
> ave(df$ageAtExam,df$subject,FUN=min)
[1] 50 50 30 30 30 40 40