环境:
R v 2.15.1在Mac OS 10.8.2上,平台x86_64-apple-darwin9.8.0/x86_64(64位),RStudio IDE设置为使用UTF-8作为其默认编码.操作系统也使用UTF-8.
> Sys.getlocale(category = "LC_ALL")
[1] "sk_SK.UTF-8/sk_SK.UTF-8/sk_SK.UTF-8/C/sk_SK.UTF-8/sk_SK.UTF-8"
Run Code Online (Sandbox Code Playgroud)
目的:
从R HTML(.Rhtml)文件生成HTML文件,其中包含带有扩展拉丁字符的图,例如š或č.
问题:
当我点击Knit HTML时,输出如下所示:
plot(1:2, main = "š?")
## Warning: conversion failure on 'š?' in 'mbcsToSbcs': dot substituted for
##
## Warning: conversion failure on 'š?' in 'mbcsToSbcs': dot substituted for
##
## Warning: conversion failure on 'š?' in 'mbcsToSbcs': dot substituted for
##
## Warning: conversion failure on 'š?' in 'mbcsToSbcs': dot substituted for
## <8d>
**Plot with correct characters despite the warnings.**
Run Code Online (Sandbox Code Playgroud)
题:
是什么导致问题以及如何解决?我怎样才能至少摆脱结果文件中显示的警告?
无望的说明:
我一直在寻找过去一两个小时的解决方案,发现了许多类似的案例,并尝试了许多不同的潜在解决方案(许多与PDF输出有关,如果我只使用Sweave,它会以同样的方式竖起),现在我确实绝望.
2012年11月9日编辑:
使用Encoding()@metasequoia建议的解决方案确实有效,但考虑到打印代码的需要,最好没有该功能,我更喜欢@nograpes使用该功能提供的解决方案pdf.options().
尽管如此,有趣的是
<!--begin.rcode
pdf.options(encoding='ISOLatin2.enc')
plot(cars, main="?ažký")
end.rcode-->
Run Code Online (Sandbox Code Playgroud)
产生相同的警告,
<!--begin.rcode
pdf.options(encoding='ISOLatin2.enc')
end.rcode-->
<!--begin.rcode
plot(cars, main="?ažký")
end.rcode-->
Run Code Online (Sandbox Code Playgroud)
按预期工作.这是为什么?我认为在R中运行命令时,时间顺序是最重要的.
因此,我的目的的明确解决方案是
<!--begin.rcode echo="FALSE"
pdf.options(encoding='ISOLatin2.enc')
end.rcode-->
Run Code Online (Sandbox Code Playgroud)
在我的每个代码的开头.
来自@metasequoia的答案有效,但我想补充几点.如果将PDF选项设置为其他编码,则无需将所有输出文本换行Encoding.在单击Knit HTML之前运行此命令:
pdf.options(encoding='ISOLatin2.enc')
Run Code Online (Sandbox Code Playgroud)
Ripley在这里的帖子中讨论了编码问题,特别是与PDF相关的问题,这可能是有意义的.值得注意的是,这种错误在Windows上不会以相同的方式发生,因为编码是以完全不同的方式处理的.
其他语言可能需要不同的编码文件,但这似乎适用于斯洛伐克语.
只是为了解释你找到的解决方案:
<!--begin.rcode
pdf.options(encoding='ISOLatin2.enc')
end.rcode-->
<!--begin.rcode
plot(cars, main="?ažký")
end.rcode-->
Run Code Online (Sandbox Code Playgroud)
这可以工作,但是当你将两行放在同一个块中时它不起作用,因为对于每个代码块,knitr打开一个新的图形设备来记录图(默认情况下它是一个PDF设备).设置为时已晚,pdf.options()因为当您放入pdf.options()并plot()使用相同的块时,设备已使用默认编码打开.
在工作解决方案中,当PDF设备为第二个块打开时,它从前一个块中的设置继承编码; 这就是它如何正确生成字符.
如果您不想在每个Rhtml文件中设置此编码选项,则可以将其放入,~/.Rprofile以便影响所有PDF设备.或者你定义自己的函数来编织Rhtml文件,例如
knit2 = function(...) {
pdf.options(encoding='ISOLatin2.enc')
knitr::knit(...)
}
Run Code Online (Sandbox Code Playgroud)
然后knit2('yourfile.Rhtml').