Get weekdays in English in R

廉价感情. 提交于 2019-11-30 06:20:27

问题


I am using R outside the US and I got everything working in English, but the result of weekdays() is still in Spanish:

Day <- seq(as.Date("2013-06-01"), by=1, len=30)
weekdays(Day)
[1] "sábado"    "domingo"   "lunes"     "martes"    "miércoles"  (...)

Any ideas on how to get the weekdays in English?


回答1:


Printing of Date and POSIX*t objects seems to be controlled by the LC_TIME locale category.

On Windows, you change it like this:

## First in Spanish
Sys.setlocale("LC_TIME","Spanish Modern Sort")
# [1] "Spanish_Spain.1252"
weekdays(Sys.Date()+0:6)
# [1] "lunes"     "martes"    "miércoles" "jueves"    "viernes"   "sábado"   
# [7] "domingo"  

## Then back to (US) English
Sys.setlocale("LC_TIME","English United States")
# [1] "English_United States.1252"
weekdays(Sys.Date()+0:6)
# [1] "Monday"    "Tuesday"   "Wednesday" "Thursday"  "Friday"    "Saturday" 
# [7] "Sunday" 

On most *NIXes, the equivalent would be:

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

The particular locale names are OS-dependent, as mentioned in ?Sys.setlocale. For names accepted by Windows, see here. For names accepted by Linux, see here.




回答2:


From my answer here, you can get weekdays in English without messing with locales like this:

c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
  "Friday", "Saturday")[as.POSIXlt(Day)$wday + 1]



回答3:


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

did the trick for me. Also this don't bring us OS reports request to set locale to "EN" cannot be honored error message.




回答4:


Under windows RStudio

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

That was the only thing that worked for me.




回答5:


I faced the very same problem trying to change the locale from es_ES to en_US (both UTF-8).

R message is given by R main workspace, as it cannot change system locale. If code is inserted into an R-script a new workspace (the running one) is created, and locale can be overriden.

In my code I included the following lines:

curr_locale <- Sys.getlocale("LC_TIME")
Sys.setlocale("LC_TIME","en_US.UTF-8")

#<specific code for graph generation>

Sys.setlocale("LC_TIME",curr_locale)

That made the change!



来源:https://stackoverflow.com/questions/17031002/get-weekdays-in-english-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!