I have a dataset that looks like this
ID date
1 2020-05-01
1 2020-06-13
2 2021-01-02
2 2021-01-02
3 2022-01-07
3 2021-12-14
And so on. There are about 30 variables in my dataset. I want to group by ID, and rewrite df$date such that only the latest date remains for each ID:
ID date
1 2020-06-13
1 2020-06-13
2 2021-01-02
2 2021-01-02
3 2022-01-07
3 2022-01-07
Date is formatted as "%Y-%m-%d"
>Solution :
You can use an if_else statement to check for latest date, and replace any date that is not the latest.
library(dplyr)
df %>%
group_by(ID) %>%
mutate(date = if_else(date == max(date), as.Date(date), as.Date(max(date))))
# A tibble: 6 × 2
# Groups: ID [3]
ID date
<int> <date>
1 1 2020-06-13
2 1 2020-06-13
3 2 2021-01-02
4 2 2021-01-02
5 3 2022-01-07
6 3 2022-01-07