首页 > 解决方案 > Encoding issue in .Rprofile at the startup of R

问题描述

I use R (v3.5.1) on Windows 10. And there is a .Rprofile file in my working directory. The file contains non-ASCII letters but is saved with UTF-8 encoding. At the startup, the encoding of non-ASCII letters is distorted. For example the code:

nth <- Sys.setlocale(locale = "Lithuanian")
print("Ą Ę Ė Į Š Č Ų")

if run at the startup results in:

[1] "Ä„ Ä\230 Ä– Ä® Å  Ä\214 Ų"

My questions are:

  1. Is it possible to configure R that it sources .Rprofile with UTF-8 encoding at the startup?
  2. Is there another way to get non-ASCII letters encoded correctly at the startup?

标签: rencodingrprofile

解决方案


很多可能的答案:

R 将.Rprofile使用当前代码页进行源代码。我不知道编码区域设置“立陶宛语”意味着什么,但是如果您以该编码而不是 UTF-8 保存文件,它可能会起作用。(我不确定您是否可以在 R 会话期间更改代码页。)

我时不时地看到 Windows 声称有一个 UTF-8 代码页。也许你可以让它工作。

如果失败,您可以切换到具有适当 UTF-8 支持(Linux、MacOS 等)的其他操作系统。

也许您可以设置两个文件:一个纯 ascii .Rprofile,它获取第二个文件,将第二个文件声明为 UTF-8。例如,把它放在你的.Rprofile

source(".RprofileUTF8.R", encoding="UTF-8")

但是,我必须警告你我无法让它工作。

您可以\uxxx对 UTF-8 字符使用转义符。你可以找到那些代码像

as.hexmode(utf8ToInt("Ą Ę Ė Į Š Č Ų"))

这表明

[1] "104" "020" "118" "020" "116" "020" "12e" "020" "160" "020" "10c" "020" "172"

所以一个等效的字符串是“\u104 \u118 \u116 \u12e \u160 \u10c \u172”,对我来说,把它放在.RprofileWindows会话中工作。


推荐阅读