How to Set the Default Language of Date in R

How to set the default language of date in R

OK, as a Q&A site, it seems an answer is required. From your description, it appears to be the issue of your locales. Read ?locales for more.

You can have a test with this (read ?strptime for various format, and pay special attention to those sensitive to locales):

format(Sys.Date(), format = "%Y-%b-%d")
# [1] "2016- 9月-06"

The output has the month in Chinese. If I want to change the display, I need to set "LC_TIME" locale to "C":

Sys.setlocale("LC_TIME", "C")

Then it is OK:

format(Sys.Date(), "%Y-%b-%d")
# [1] "2016-Sep-06"

Every time you start a new R session, you get back to native setting. Should you want a permanent change, put

.First <- function() {
Sys.setlocale("LC_TIME", "C")
}

in the $(R RHOME)/etc/Rprofile.site file. Read ?Startup for how to customize R startup and the use of .First.

How to change language settings in R

You can set this using the Sys.setenv() function. My R session defaults to English, so I'll set it to French and then back again:

> Sys.setenv(LANG = "fr")
> 2 + x
Erreur : objet 'x' introuvable
> Sys.setenv(LANG = "en")
> 2 + x
Error: object 'x' not found

A list of the abbreviations can be found here.

Sys.getenv() gives you a list of all the environment variables that are set.

R: How to convert date with %b for different languages

?as.POSIXct gives:

If format is specified, remember that some of the format
specifications are locale-specific, and you may need to set the
LC_TIME category appropriately via Sys.setlocale. This most often
affects the use of %b, %B (month names) and %p (AM/PM).

Try to call Sys.setlocale() before using %b.

R converting datetime format in foreign language not working

See here https://github.com/tidyverse/lubridate/issues/781

Sys.setlocale("LC_TIME", "Spanish_Spain.1252")
format <- "%a@%A@%b@%B@%p@"
enc2utf8(unique(format(lubridate:::.date_template, format = format)))
str(lubridate:::.get_locale_regs("Spanish_Spain.1252"))
library(lubridate)

Sys.getlocale("LC_TIME")
[1] "Spanish_Spain.1252"

parse_date_time(fechas, 'ymd HM')
[1] "2016-06-15 08:39:00 UTC" "2016-04-02 08:39:00 UTC" "2016-12-02 08:39:00 UTC"


Related Topics



Leave a reply



Submit