0

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)
Quinten
  • 35,235
  • 5
  • 20
  • 53
Ed_Gravy
  • 1,841
  • 2
  • 11
  • 34
  • 2
    You can't extract after formatting as it is not `Date` class. You need `year(lubridate::mdy(date))` – akrun Sep 29 '22 at 17:02
  • 1
    When you run `mdy()` on your string, that converts it to `Date` class. When you run `format()` on your date, you convert it to `character` class. The `year()` function needs to be run on a `Date`. – Gregor Thomas Sep 29 '22 at 17:04
  • 1
    A note on your `# Create a proper date column with the desired format` comment: I would consider "a proper date column" to be a column with class `Date`, which will print in `YYYY-MM-DD` format. If your desired format is `MM-DD-YYYY`, you are choosing that format **instead of** a proper date column. – Gregor Thomas Sep 29 '22 at 17:40

1 Answers1

1

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

Quinten
  • 35,235
  • 5
  • 20
  • 53