What is a reliable way to change and then change the locale in R?

Inside the function, I want to change the locale, do something, and then replace it. Because the side effects are bad.

old_locale <- Sys.getlocale() # do some stuff Sys.setlocale(old_locale) 

However, Sys.setlocale requires the category and locale argument.

Sys.getlocale() , Sys.getlocale() other hand, gives me the following:

 "LC_COLLATE=English_Australia.1252;LC_CTYPE=English_Australia.1252;LC_MONETARY=English_Australia.1252;LC_NUMERIC=C;LC_TIME=English_Australia.1252" 

Ok Maybe I can handle this:

 old_locale <- Sys.getlocale() locale_key_values <- strsplit(strsplit(old_locale, ';')[[1]], '=')[[1]], '=') locale_keys <- lapply(locale_key_values, getElement, name=1) locale_values <- lapply(locale_key_values, getElement, name=2) # do some stuff mapply(Sys.setlocale, category=locale_keys, locale=locale_values) 

The problem is solved!

... or that?

 Sys.setlocale(locale='C') 

Sys.getlocale() now returns "C" ! This will not work with my keyword parser.

And I suddenly realize that I don’t know anything about locales or the range of strings that Sys.getlocale() can return.

Does anyone know of a reliable way to save and restore locale state?

+5
source share
1 answer

?Sys.getlocale says:

For category = "LC_ALL" the string details are system category = "LC_ALL" : it can be a single locale name or a set of language names separated by "/" (Solaris, OS X) or ";" (Windows, Linux). For portability, it is best to query categories separately: this is not necessary so the result foo <- Sys.getlocale() can be used in Sys.setlocale("LC_ALL", locale = foo) .

So you need to do something like:

 localeCategories <- c("LC_COLLATE","LC_CTYPE","LC_MONETARY","LC_NUMERIC","LC_TIME") locales <- setNames(lapply(localeCategories, Sys.getlocale), localeCategories) 

Even better, you should determine which locale settings you need to change, and only change the units you need. For example, you may need to change LC_TIME if you are processing character strings for date and time, or you may need to change LC_COLLATE if you need to change the sort order of a character string.

+5
source

All Articles