简体   繁体   English

如何使用knitr :: spin显示/打印中文字符

[英]How to display/print Chinese characters with knitr::spin

I have recently began using knitr::spin() to quickly convert my code into into html reports and so far it has been amazing. 我最近开始使用knitr :: spin()将我的代码快速转换为html报告,到目前为止它一直很棒。

However, I have run into a problem when attempting to include Chinese characters in either text or the code sections. 但是,在尝试在文本或代码部分中包含中文字符时遇到了问题。 Here is a short example: 这是一个简短的例子:

not_working.R not_working.R

#' # Sample document
#' 
#' Some text. 
#' 还有汉字。
#+

print("Some text")
print("他喜欢吃炒面")

#'

To generate output, I use: 要生成输出,我使用:

knitr::spin("not_working.R")

The characters are distorted in the following manner: 字符以下列方式扭曲:

Sample document

Some text.

杩樻湁姹夊瓧銆

print("Some text")
## [1] "Some text"

print("浠栧枩娆㈠悆鐐掗潰")
## [1] "<U+00E4><U+00BB>–<U+013A>–<U+015B><U+0107><U+00AC><U+02D8><U+013A> 
<U+0090><U+0083><U+00E7><U+201A>’é<U+0165><U+02D8>"

I have tried setting my locale (both within the script and within .Rprofile). 我尝试过设置我的语言环境(在脚本和.Rprofile中)。 This has allowed me to display the characters in RStudio and in its console output, but not in the cases above. 这允许我在RStudio和控制台输出中显示字符,但不是在上面的情况下。

I also tried doing File/Save with Encoding --> UTF-8 我也尝试使用编码进行文件/保存 - > UTF-8

I am using Windows 7. 我使用的是Windows 7。

This problem does not occur if I create an R notebook myself (which seems to suggest that the problem might be at .R to .md conversion). 如果我自己创建一个R笔记本(这似乎表明问题可能是.R到.md转换),则不会出现此问题。 The following works fine: 以下工作正常:

working.Rmd working.Rmd

---
title: "R Notebook"
output: html_notebook
---
他喜欢吃炒面

```{r}
print("他喜欢吃炒面")
```

My ultimate aim is to import an (UTF-8 encoded) text file, do analysis and display the interim results, all within the html report. 我的最终目标是在html报告中导入(UTF-8编码的)文本文件,进行分析并显示中间结果。

Is there any way to fix this problem? 有什么方法可以解决这个问题吗?

由于knitr 1.21knitr::spin()只接受以UTF-8编码的R脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM