Keep only the most recent date

Viewed 177

I have this data

data;code
18/02/2020;C106
05/04/2018;C107
11/09/2016;C107
16/02/2019;C109
11/03/2020;C110
04/03/2020;C114
18/02/2020;C114
06/02/2020;C121

I would like to select the most recent date for each code, like this:

data;code
18/02/2020;C106
05/04/2018;C107
16/02/2019;C109
11/03/2020;C110
04/03/2020;C114
06/02/2020;C121

I tried:

tapply(data$data, data$code, max)

But I received this:

Error in Summary.factor(7L, na.rm = FALSE) : 
  ‘max’ not meaningful for factors 
2 Answers

With dplyr, after grouping by 'code', slice the row where the data is max

library(dplyr)
library(lubridate)
data %>%
    group_by(code) %>%
    slice(which.max(dmy(data)))

Or in base R, we can use aggregate

aggregate(cbind(data = as.Date(data, '%d/%m/%Y')) ~ code, data, max)

This uses dplyr and lubridate to format the data column, group by the code column, and filter on the most recent (last) date for each code.

library(dplyr)
library(lubridate)

df %>% 
  mutate(data = dmy(data)) %>% 
  group_by(code) %>% 
  filter(data == last(data))
Related