Tdebeus
Tdebeus

Reputation: 1599

Converting character dates with R package lubridate fails to parse

I try to convert the following character vector into a date class.

> library(lubridate)
> unemployment_rate$month

 [1] "2017-1-1"  "2017-2-1"  "2017-3-1"  "2017-4-1"  "2017-5-1"  "2017-6-1"  "2017-7-1"  "2017-8-1"  "2017-9-1"  "2017-10-1" "2017-11-1" "2017-12-1"
[13] "2016-1-1"  "2016-2-1"  "2016-3-1"  "2016-4-1"  "2016-5-1"  "2016-6-1"  "2016-7-1"  "2016-8-1"  "2016-9-1"  "2016-10-1" "2016-11-1" "2016-12-1"

But when I try to convert the dates with the lubridate package I get the following results and warning message:

> unemployment_rate$month <- ymd(unemployment_rate$month, "%Y-%m-%d")

Error in `$<-.data.frame`(`*tmp*`, "month", value = c(17167, 17198, 17226,  : 
  replacement has 25 rows, data has 24
In addition: Warning message:
1 failed to parse.

I can't understand why replacement has 25 rows while the data has actualy 24 rows (two years), also which date is so different that 1 failed to parse.?

Maybe useful thing to know, I created had originally had to create (concatonated and month.abb) the month vector myself from: two columns with one month column formatted "jan', "feb" etc. and a year column formatted "2016" and "2017".

Upvotes: 1

Views: 2249

Answers (1)

pasipasi
pasipasi

Reputation: 1226

You have a vector of length 24 but you're adding "%Y-%m-%d" as 25th date. ymd() fails to parse "%Y-%m-%d"

> lubridate::ymd("2017-1-1")
[1] "2017-01-01"
> lubridate::ymd("2017-1-1", "%Y-%m-%d")
[1] "2017-01-01" NA          
Warning message:
 1 failed to parse. 

Upvotes: 3

Related Questions