I have spent hours today to find a solution to this, there are similar threads out there but not quite what I need.
Dataset:
Year <- c(2019, 2020, 2021, 2019, 2020, 2020, 2021, 2021)
Term <- c("2019_T1", "2020_T1", "2021_T1", "2019_T1", "2020_T1", "2020_T2", "2021_T1", "2021_T2")
Code <- c(1,1,1,2,2,2,2,2)
Description <- c("Desc1","Desc1","Desc1", "Desc2", "Desc2", "Desc2", "Desc2_NotRecent","Desc2_Recent")
This produces a table as follows:
Year Term Code Description
1 2019 2019_T1 1 Desc1
2 2020 2020_T1 1 Desc1
3 2021 2021_T1 1 Desc1
4 2019 2019_T1 2 Desc2
5 2020 2020_T1 2 Desc2
6 2020 2020_T2 2 Desc2
7 2021 2021_T1 2 Desc2_NotRecent
8 2021 2021_T2 2 Desc2_Recent
Question: How to add a column to show the most recent Description for each Code.
I will need to find the most recent based on the Term. Perhaps this can be accomplished by a simple sort first, apologies I have not figured this out.
Its important its the most recent Term value. Here, the most recent Term is 2021_T2. If the first value is selected, it could be an old description and confuse stakeholders.
Outcome I need:
Year Term Code Description Most_Recent
1 2019 2019_T1 1 Desc1 Desc1
2 2020 2020_T1 1 Desc1 Desc1
3 2021 2021_T1 1 Desc1 Desc1
4 2019 2019_T1 2 Desc2 Desc2_Recent
5 2020 2020_T1 2 Desc2 Desc2_Recent
6 2020 2020_T2 2 Desc2 Desc2_Recent
7 2021 2021_T1 2 Desc2_NotRecent Desc2_Recent
8 2021 2021_T2 2 Desc2_Recent Desc2_Recent
Really grateful for all of the help. Edited to include simple solution from Robin Gertenbach.
df %>%
group_by(Code) %>%
dplyr:: mutate(Most_Recent = dplyr::last(Description, Term))