In my dataset respondents are grouped together and there is data available about their age. I want all the people in the same group to have the value of the oldest person in that group.
So my example data looks like this.
df <- data.frame(groups = c(1,1,1,2,2,2,3,3,3),
age = c(12, 23, 34, 13, 24, 35, 13, 25, 36),
value = c(1, 2, 3, 4, 5, 6, 7, 8, 9))
> df
groups age value
1 1 12 1
2 1 23 2
3 1 34 3
4 2 13 4
5 2 24 5
6 2 35 6
7 3 13 7
8 3 25 8
9 3 36 9
And I want it to look this this
> df
groups age value new_value
1 1 12 1 3
2 1 23 2 3
3 1 34 3 3
4 2 13 4 6
5 2 24 5 6
6 2 35 6 6
7 3 13 7 9
8 3 25 8 9
9 3 36 9 9
Any idea how to do this with dplyr?
I have tried something like this, but it doesn't work
df %>%
group_by(groups) %>%
mutate(new_value = df$value[which.max(df$age)])