-2

I have a factor variable which I would to transform in Date. When I try using as.Date() It shows me the error:

Error in charToDate(x) : character string is not in a standard unambiguous format

My data are these:

[1] Aug 31, 2018 Aug 30, 2018 Aug 29, 2018 Aug 28, 2018 Aug 27, 2018 Aug 26, 2018
[7] Aug 25, 2018 Aug 24, 2018 Aug 23, 2018 Aug 22, 2018 Aug 21, 2018 Aug 20, 2018
[13] Aug 19, 2018 Aug 18, 2018 Aug 17, 2018 Aug 16, 2018 Aug 15, 2018 Aug 14, 2018
[19] Aug 13, 2018 Aug 12, 2018 Aug 11, 2018 Aug 10, 2018 Aug 09, 2018 Aug 08, 2018
[25] Aug 07, 2018 Aug 06, 2018 Aug 05, 2018 Aug 04, 2018 Aug 03, 2018 Aug 02, 2018

How could I transform in Date in the format %d-%m-%Y?

La_haine
  • 339
  • 1
  • 6
  • 18
  • Possible duplicate of [R - converting dates within data.frame](https://stackoverflow.com/questions/52222856/r-converting-dates-within-data-frame) – Saurabh Chauhan Sep 11 '18 at 08:24

3 Answers3

1

Try with format = "%b %d, %Y":

ss <- c("Aug 31, 2018", "Aug 30, 2018", "Aug 29, 2018", "Aug 28, 2018", "Aug 27, 2018", "Aug 26, 2018")

as.Date(ss, format = "%b %d, %Y")
#[1] "2018-08-31" "2018-08-30" "2018-08-29" "2018-08-28" "2018-08-27"
#[6] "2018-08-26"

For details what the different conversion specifications (e.g. "%b", "%Y" etc.) mean, take a look at ?strptime.

By the way, there is no need to manually convert from factor to character, because as.Date has a method for factors which converts factors to character vectors, see as.Date.factor.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

specify the format within the function as.Date

as.Date(MyData, format="%b %d, %Y")
Sayuri
  • 94
  • 8
  • It gives me a lot of NAs and some good data. It seems that doesn't recognize some months of the Year, like May and June. – La_haine Sep 11 '18 at 07:53
  • Could you show us how your format of the days in May and June looks like? – Sayuri Sep 11 '18 at 08:00
  • The format is the same as for the other months. It looks like: **May 19, 2018**. The format is the same for all of these ('"%m %d, %Y"'), but for some months it turns NAs. – La_haine Sep 11 '18 at 08:03
  • 1
    I could imagine that your language settings are not English... therefore it doesn't recognize "May" -> look herefor more information: https://stackoverflow.com/questions/17031002/get-weekdays-in-english-in-r – Sayuri Sep 11 '18 at 08:17
  • You were right! It was in Italian! I solved the problem simply getting 'Sys.setlocale("LC_TIME", "English")' in the console! Thank You very much! – La_haine Sep 11 '18 at 08:23
0

I've solved the problem getting this code Sys.setlocale("LC_TIME", "English") into the console!

La_haine
  • 339
  • 1
  • 6
  • 18