求助:已设置R语言为英文,RStudio中R Markdown日期仍非英文
Hey there! I noticed you’ve already tried adjusting R’s locale settings to get English dates in your R Markdown documents, but they’re still not showing up correctly. Let’s tackle this—here are some tailored solutions for your Windows 7 setup:
1. Target Date/Time Locale Directly in R Markdown
R Markdown runs in a separate R session, so the locale settings from your main console won’t automatically carry over. Add this line at the very top of your R Markdown document (before any other code or YAML):
Sys.setlocale(category = "LC_TIME", locale = "English_United States.1252")
We use LC_TIME specifically here because it only affects date and time formatting (which is exactly what you need for markdown dates). For Windows 7, this locale string should be valid—you can confirm your system’s available time locales with Sys.getlocale("LC_TIME") if you need to tweak it.
2. Set a Global Default for All R Sessions
If you want every new R Markdown file to use English dates automatically, add the locale setting to your .Rprofile file:
- Open a new R script and run
path.expand("~")to find your user directory (e.g.,C:\Users\YourName) - Create a file named
.Rprofilein that directory (make sure it doesn’t have a.txtextension) - Add this code to the file:
# Set English date locale for Windows if (Sys.info()["sysname"] == "Windows") { Sys.setlocale(category = "LC_TIME", locale = "English_United States.1252") }
- Restart RStudio—this setting will now apply to every R session, including those launched by R Markdown.
3. Explicitly Define Date Format in YAML
You can also force the date format directly in your R Markdown’s YAML frontmatter. This bypasses locale settings entirely if you prefer:
--- title: "Your Document Title" date: "`r format(Sys.Date(), '%B %d, %Y')`" # Outputs "October 05, 2024" output: html_document ---
Use these format codes to adjust the date:
%B: Full English month name (e.g., October)%b: Abbreviated month (e.g., Oct)%d: Two-digit day%Y: Four-digit year
From your sessionInfo(), you’re running R 3.4.4 on Windows 7—these solutions should work perfectly for your setup. If you’re still having issues, try restarting RStudio after making changes to ensure the new settings take effect.
内容的提问来源于stack exchange,提问作者HW-Scientist

