The data looks like this.
id<-c(rep(102,9),rep(103,5),rep(104,4))
status<-rep(c('single','relationship','relationship','single','single','single'),3)
age<-c(17:19,22,23,26,28,32,33,21:25,21:24)
data<-data.frame(id,status,age)
I would like to select only rows that are the OLDEST age observation row of single and YOUNGEST observation of relationship for each id, each time the status changes. (STEP 1)
The end product should look like this
newdata<-data[c(1,2,7,8,13,14,18),]
The next step is to change it into wide form, which I think I can do. (STEP 2)
long<-newdata %>%
group_by(id,status) %>%
mutate(dummy=row_number(),
status2=paste0(status,dummy)) %>%
ungroup() %>%
select(id,status2,age) %>%
pivot_wider(names_from = status2,values_from = age)
What I am not sure how to do is to code for STEP 1. I can only think of using slice_min and slice_max but that really depends on the status and also can occur multiple times for the same id.
Also perhaps there's a more clever way to combine step 1 and 2.