【问题标题】:Is there a knitr option to force UTF-8 encoding in included R files?是否有 knitr 选项可以在包含的 R 文件中强制使用 UTF-8 编码?
【发布时间】:2013-03-20 04:21:28
【问题描述】:

我正在使用 Windows 7、R2.15.3 和 RStudio 0.97.320 和 knitr knitr_1.1.6(在亿辉 3 月 12 日修复“编码:knitr 和子文件”问题后下载)

> sessionInfo()
R version 2.15.3 (2013-03-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=Spanish_Argentina.1252  LC_CTYPE=Spanish_Argentina.1252    LC_MONETARY=Spanish_Argentina.1252
[4] LC_NUMERIC=C                       LC_TIME=Spanish_Argentina.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] lattice_0.20-13    pixmap_0.4-11      RColorBrewer_1.0-5 ade4_1.5-1         pander_0.3.1      
[6] xtable_1.7-1      

loaded via a namespace (and not attached):
[1] digest_0.6.3   evaluate_0.4.3 formatR_0.7    grid_2.15.3    knitr_1.1.6    stringr_0.6.2  tools_2.15.3 

我的 R 代码在一个类似这样的文件中:

## @knitr RunMyCode 
print('Called from .R file: á é í ó ú ñ')  

# Workaround
my.text <- 'á é í ó ú ñ'
Encoding(my.text) <- "UTF-8"
print(my.text)

我从 Rmd 文件中调用它,例如:

Title
========================================================
Spanish text: á é í ó ú ñ

Use it from .Rmd code: it comes out right...
```{r}
print('á é í ó ú ñ')
```

```{r ReadFunctions, cache=FALSE, echo=TRUE, eval=TRUE}
read_chunk('TestSpanishText.R')
```

Spanish text comes out garbled here:
```{r RunMyCode, echo=TRUE, eval=TRUE, cache=TRUE, dependson=c('ReadFunctions')}
``` 

我的问题是在 .R 文件(在 RStudio 中以 UTF-8 编码)中键入的西班牙语字符。如果在 Rmd 文件中输入这些字符是可以的(父文件和子文件都可以正常工作),但在 R 文件中则不然。正如您在下面看到的,Encoding() 确实提供了一种解决方法,但我想知道是否还有其他方法,例如全局选项?如果我使用 Encoding(),我会在 RStudio 控制台中遇到逆问题...

Title

Spanish text: á é í ó ú ñ

Use it from .Rmd code: it comes out right...

print("á é í ó ú ñ")
## [1] "á é í ó ú ñ"
read_chunk("TestSpanishText.R")

Spanish text comes out garbled here:    
print("Called from .R file: á é í ó ú ñ")
## [1] "Called from .R file: á é í ó ú ñ"

# Workaround
my.text <- "á é í ó ú ñ"
Encoding(my.text) <- "UTF-8"
print(my.text)
## [1] "á é í ó ú ñ"

谢谢!

【问题讨论】:

    标签: r utf-8 character-encoding knitr


    【解决方案1】:

    理想情况下,我应该在read_chunk() 中有一个encoding 参数,但由于您使用的是UTF-8,这可能有效:

    read_chunk(lines = readLines("TestSpanishText.R", encoding = "UTF-8"))
    

    请先试试这个。如果它不起作用,我将添加一个encoding 参数。无论如何,我确信这肯定有效(只是稍微长一点):

    con = file("TestSpanishText.R", encoding = "UTF-8")
    read_chunk(con)
    close(con)
    

    【讨论】:

    • 我尝试了这种方法 (con = file("TestSpanishText.R", encoding = "UTF-8"); read_chunk(con);close(con)) 来解决我的问题:stackoverflow.com/questions/48307007/…,但无法使其正常工作。 ???
    猜你喜欢
    • 1970-01-01
    • 2018-05-21
    • 2012-02-06
    • 2011-08-25
    • 1970-01-01
    • 2011-08-07
    • 2011-08-19
    相关资源
    最近更新 更多