qoheleth
qoheleth

Reputation: 2309

knitr compiling document with chinese

I try compiling YiHui's BIG5 example (knitr with chinese content). I used Mac OSX snowleopard, latest RStudio, pdfLatex (same result with XeLatex). This is an excerpt of the raw .Rnw

\begin{document}
\title{knitr與繁體中文文檔}
\author{謝益輝}

測試,咳咳。以下代碼靠譜嗎?

<<test>>=
1+1 # 太簡單了
'引號能用嗎?'
rnorm(5)
(function(){
paste('這裡是字符串')
})()
@

Using the system default encoding "UTF-8" the resulting pdf is

1+1 #
## [1] 2
''
## [1] ""
rnorm(5)
## [1] -0.4290 1.8835 -0.7045 -0.9232 1.5433
(function(){ paste('') })()
## [1] ""

as you can see the chinese are just blank space. Then I saved the .Rnw with BIG5 encoding and compile again. The resulting pdf becomes:

AyyCHUNXaH
1+1 # F
## [1] 2
'H'
## [1] "H"
rnorm(5)
## [1] -0.27859 -0.79428 -0.76903 0.40313 -0.07851
(function(){ paste('oOr') })()
## [1] "oOr"

This time the chinese becomes some random letters.

What else can I do? Completely newbie w.r.t. encoding/locale.

Upvotes: 5

Views: 1538

Answers (2)

Chun Wan Mo
Chun Wan Mo

Reputation: 1

Hi you may try these code below.

Sys.setlocale(category="LC_ALL",locale="en_US.UTF-8") 

However, it doesn't guarantee the random letter problem would be gone because I had the same problem with my R installation as well. My OS is Chinese. This problem is completely solved when I changed my OS to MAC. Hope it helps.

Upvotes: 0

Yihui Xie
Yihui Xie

Reputation: 30114

You have to set up Chinese fonts for XeLaTeX, which I did not do in my example because I have no idea what fonts I should use for Traditional Chinese, and it is not easy to provide a portable solution across different operating systems because I do not know what fonts are available. You may take a look at the xeCJK package.

Upvotes: 3

Related Questions