0

I am working through the book 'R for dummies', 2nd Edition, John Wiley & Sons, Inc. In chapter 6 you try adding time information into the vector but the shown code is not working:

Book:

apollo <- "July 20, 1969, 20:17:39"
apollo.fmt <- "%B %d, %Y, %H:%M:%S"
xct <- as.POSIXct(apollo, format = apollo.fmt, tz = "UTC")
xct
#> [1] "1969-07-20 20:17:39 UTC"

My try:

apollo <- "July 20, 1969, 20:17:39"
apollo.fmt <- "%B %d, %Y, %H:%M:%S"
xct <- as.POSIXct(apollo, format = apollo.fmt, tz = "UTC")
xct
#> [1] NA

Anyone knows what I am doing wrong, and what should be the right code?

EzraSQL
  • 3
  • 3
  • Working fine for me. Restart your R session and run your code. – UseR10085 Jul 18 '20 at 06:21
  • 1
    @BappaDas Probably a locale issue, mine is not a English locale and the result is `NA`. Try to see what `Sys.getlocale("LC_TIME")` returns. The month name needs to be changed? – Rui Barradas Jul 18 '20 at 06:29
  • This results in: "Dutch_Netherlands.1252" However all other date- and time-related examples are working, so I do not really see why this could be an issue. – EzraSQL Jul 18 '20 at 06:46
  • @EzraSQL do the other examples have full English month names? Maybe try changing "July" to "Juli" if you're in a Dutch locale? – Allan Cameron Jul 18 '20 at 07:19

1 Answers1

4

This is a locale problem, months in your language have other names than in English (for %B in date format), that's why it fails. It simply cannot recognize "July" in apollo string as a month, because it searches for month names in your language.

Try to set English locale for dates and times by running:

Sys.setlocale(category = "LC_TIME", locale = "English")

or set English locale for all categories (monetary, numeric etc.):

Sys.setlocale(category = "LC_ALL", locale = "English")

For details, see Sys.setlocale()).

See this example (my default locale is Czech, so your code returns NA in my case as well):

apollo <- "July 20, 1969, 20:17:39"
apollo.fmt <- "%B %d, %Y, %H:%M:%S"
xct <- as.POSIXct(apollo, format = apollo.fmt, tz = "UTC")
xct
#> [1] NA

Sys.setlocale(category = "LC_TIME", locale = "English")
#> [1] "English_United States.1252"

apollo <- "July 20, 1969, 20:17:39"
apollo.fmt <- "%B %d, %Y, %H:%M:%S"
xct <- as.POSIXct(apollo, format = apollo.fmt, tz = "UTC")
xct
#> [1] "1969-07-20 20:17:39 UTC"

Created on 2020-07-18 by the reprex package (v0.3.0)