【问题标题】:Encoding within chunks results in missing characters despite UTF-8尽管 UTF-8,但在块内编码会导致字符丢失
【发布时间】:2020-12-20 16:30:07
【问题描述】:

我有一个用 UTF-8 编码的 Rmd 文件,但是当我编织该文件时,R 评估的内联和块内容缺少一些捷克语字符。当我在块之外键入文本时,一切都很好。从文件中读取相同的文本,我可以正确地产生内联输出,但不能在块中使用打印(printcat)。我对这种情况完全感到困惑,尤其是 cat 的行为。

我在 Windows 上。在控制台中检查编码会返回 UTF-8。区域设置为 English_United Kingdom.1252。

---
title: "test"
output: html_document
---
```{r}
txt <- "Čeština funguje"
print(Encoding(txt))
print(txt)      # prints incorrectly
```

Čeština funguje # prints correctly
`r txt`         # prints incorrectly

```{r}
cat(txt)        # prints incorrectly
```

```{r, results='asis'}
line <- readLines("line", encoding = "UTF-8")
print(Encoding(line))
print(line) # prints incorrectly
cat(line)   # prints incorrectly
```

`r line`    # prints correctly!

附:我知道关于 Windows 上的 R 和编码有很多说法,但是尽管我进行了广泛的搜索,但我找不到解决方案,也不完全理解这种行为。我猜我需要设置一些语言环境,但到目前为止我的努力都是徒劳的。

【问题讨论】:

    标签: r encoding r-markdown knitr


    【解决方案1】:

    R supports UTF-8 natively on Windows 之前,如果您想使用该语言的多字节字符,通常您必须将语言环境设置为特定语言,例如,如果您想正确使用,则需要使用捷克语言环境而不是英语@ 987654323@/cat()捷克语字符。需要在编织之前设置语言环境,例如,您可以在 ~/.Rprofile 中设置它:

    Sys.setlocale(, 'Czech')
    

    我以前从未使用过捷克语并且不确定'Czech' 是否是一个合适的值,但这就是我的想法(我之前在其他语言方面也取得了成功)。

    【讨论】:

    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多