1

I have data that has dates in a character format, as "JAN2005","FEB2005","MAR2005", such as :

Test <- data.table(c("JAN2005","FEB2005","MAR2005","APR2005"),c(436.6,543.1,417.3,687.4))

Is there a simple way to get the date in an actual date format ?

Anthony Martin
  • 767
  • 1
  • 9
  • 28
  • 2
    Try `Test[, V1 := as.Date(zoo::as.yearmon(V1))]` – akrun Jan 23 '20 at 23:02
  • I get no error message, but it does not work : the output is filled with – Anthony Martin Jan 23 '20 at 23:07
  • Not sure about your error. Based on the example showed, it get `Test$V1 [1] "2005-01-01" "2005-02-01" "2005-03-01" "2005-04-01"` – akrun Jan 23 '20 at 23:07
  • 1
    Or with `base R` `Test[, V1 := as.Date(paste0(V1, '01'), "%b%Y%d")]# > Test$V1 [1] "2005-01-01" "2005-02-01" "2005-03-01" "2005-04-01"` – akrun Jan 23 '20 at 23:12
  • Hmm, I get also NAs... Maybe a package issue – Anthony Martin Jan 23 '20 at 23:17
  • I am using only your example on `R 3.6.2` – akrun Jan 23 '20 at 23:17
  • I am in R 3.6.1 and a bit puzzled. I have a few additional packages – Anthony Martin Jan 23 '20 at 23:25
  • 1
    May be it is related to the locale i.e. if your locale settings are different, then it may not match the month. According to `?strptime` `%b -Abbreviated month name in the current locale on this platform. (Also matches full name on input: in some locales there are no abbreviations of names.)` – akrun Jan 23 '20 at 23:29
  • 1
    My locale info is `locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8` – akrun Jan 23 '20 at 23:31
  • Maybe you are on something, I am French and my locale seems to be in French : `"LC_COLLATE=French_France.1252;LC_CTYPE=French_France.1252;LC_MONETARY=French_France.1252;LC_NUMERIC=C;LC_TIME=French_France.1252"` – Anthony Martin Jan 23 '20 at 23:35
  • You can change it to US or English. that is the isssue – akrun Jan 23 '20 at 23:37
  • 1
    Please check [here](https://stackoverflow.com/questions/16347731/how-to-change-the-locale-of-r) for setting the locale – akrun Jan 23 '20 at 23:38
  • It does work indeed. I changed the locale using `Sys.setlocale("LC_ALL","English") `. Thank you a lot for your help – Anthony Martin Jan 23 '20 at 23:41

1 Answers1

1

We can use as.yearmon from zoo

library(data.table)
Test[, V1 := as.Date(zoo::as.yearmon(V1))]

Or convert to a proper 'Date' by pasteing the day as well and then use as.Date

Test[, V1 := as.Date(paste0(V1, '01'), "%b%Y%d")]

If the locale is different from English, change it to match the 'month' as it is in English

Sys.setlocale("LC_ALL","English")
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I am going to accept your answer, but it might be useful to add a note about the locale ? Or maybe I should ask another question about that ? – Anthony Martin Jan 23 '20 at 23:45