Reputation: 77
This may seem to be pretty easy but I dont know where I'm going wrong. I have a character vector with dates of form "January 2012", "March 2012"
and so on. I have tried a few different codes but none of them seems to work and returns NA
values.
Code1:
as.POSIXct(df$date, format = "%Y %B")
returns NA
vales
Code2:
as_date(df$date, format= NULL)
returns NA
values and the warning message:
Warning message:
All formats failed to parse. No formats found.
Code3:
as.Date(df$date, "%Y %B")
returns NA
values and the warning message:
Warning message:
In strptime(x, format, tz = "GMT") : unknown timezone 'PLT-3PLT'
Upvotes: 1
Views: 246
Reputation: 173813
A date needs to include the day of the month. Typically in dealing with month-only data, we would use the first of the month. The solution is therefore to paste a 1 to the front of each string and use the format "%d %Y %B"
as shown in this reproducible example:
df <- data.frame(date = c('2022 January', '2022 March'))
as.POSIXct(paste(1, df$date), format = "%d %Y %B")
#> [1] "2022-01-01 GMT" "2022-03-01 GMT"
Created on 2022-09-29 with reprex v2.0.2
Upvotes: 3