Search code examples
rlubridate

lubridate extract year from date column


Based on the data and code below, when I try to extract year from the date column, I get the following error:

Error in as.POSIXlt.character(x, tz = tz(x)) : 
  character string is not in a standard unambiguous format 

Purpose: Create year and month columns from the date column

Data + code:

library(lubridate)

# Create sample dates
date = c("1/6/2022", "1/6/2022", "1/19/2022", "1/20/2022")

# Create a proper date column with the desired format
date_final = format(lubridate::mdy(date), '%m-%d-%Y')

# Create a year column from `date_final`
Year = lubridate::year(date_final)

Solution

  • base R option using format with as.POSIXct:

    date = c("1/6/2022", "1/6/2022", "1/19/2022", "1/20/2022")
    dates <- as.POSIXct(date, format = '%m/%d/%Y')
    format(dates, format = '%Y')
    #> [1] "2022" "2022" "2022" "2022"
    

    Created on 2022-09-29 with reprex v2.0.2