-3

I am sorry but I struggle with this:

mydate <- factor("2016-10-25")
as.Date(mydate, format = "%Y-%M-%D")

it returns NA. Any ideas? Thanks!

cs0815
  • 16,751
  • 45
  • 136
  • 299
  • Try `as.Date(mydate, format = "%Y-%m-%d")`. Some more info on the formats here: https://www.statmethods.net/input/dates.html – AntoniosK Nov 09 '18 at 11:53
  • Similar answer here: [link]https://stackoverflow.com/questions/17496358/r-help-converting-factor-to-date – Jamie_D Nov 09 '18 at 11:53
  • Look up format codes with `?strptime`. – jay.sf Nov 09 '18 at 11:56
  • um `as.Date(mydate)` works _just fine_ since that's the default ISO format it expects – hrbrmstr Nov 09 '18 at 12:23
  • 3
    Suggesting the use of `lubridate` for this example is crazy talk. It's the default ISO format and I don't think anyone rly wants to take **1250** microseconds to do the conversion (for _one_ element) when the built-in `as.Date()` does it in **30** microseconds. – hrbrmstr Nov 09 '18 at 12:25

2 Answers2

3

You need to use small letters for month and day ("%Y-%m-%d") instead of capital letters ("%Y-%M-%D").

mydate <- factor("2016-10-25")
as.Date(mydate, format = "%Y-%m-%d")

"2016-10-25"

enter image description here

Can H.
  • 352
  • 1
  • 3
  • 12
  • well I tried this - I think but yes this works now. Thanks! – cs0815 Nov 09 '18 at 12:01
  • You might want to also add the output of `microbenchmark::microbenchmark(base = as.Date(mydate), lubr = lubridate::ymd(mydate))` to this answer to show the stark contrast to `lubridate` (also the `format` string is not necessary since it'll try the ISO format one by default) – hrbrmstr Nov 09 '18 at 12:28
2

You can use lubridate as follows:

    mydate <- factor("2016-10-25")
require(lubridate)
ymd(mydate)
NelsonGon
  • 13,015
  • 7
  • 27
  • 57