I have a column in my dataset which is formatted as dates. I am aiming to obtain the most recent date by using the max() function. The date column is formatted like (ex. 21.12.2018), and I have used the folowing lines of code:
MD$Date<- as.Date(MD$Date, "%d.%m.%Y")
analysis_date <- max(MD$Date)
Howevere, analysis_date returns the value NA. Any tips?
CodePudding user response:
Here an exemple using dplyr
from tidyverse
:
# package
library(dplyr)
# Sample database
MD <- data.frame(
Date = c("21.12.2018", NA, "20.12.2018", "19.12.2018")
)
# Get the most recent date
MD |>
slice_max(
as.Date(Date, "%d.%m.%Y")
)
CodePudding user response:
I think the reason it returns the NA is that your date is in character you need to convert your dataset from character to date format.
my_dates_update <- as.Date(my_dates) # Convert character to Date
class(my_dates_update) # Check the class of updated dates, it should return date as type
min(my_dates_updated) # Earliest date
max(my_dates_updated) # Latest date