在UTF-8中,tikzDevice不会在Windows下输出带有Umlauts的代码
我用RMarkdown编写了一份报告,并使用tikzDevice进行绘图。当我使用德语Umlauts (Ö)时,RStudio抛出以下错误:
Data.Text.Internal.Encoding.streamDecodeUtf8With::无法解码字节‘\xd6 6’:Data.Text.Internal.Encoding.streamDecodeUtf8With:无效的UTF-8流
下面是一个很小的例子:
---
title: "test"
author: "test"
date: "Today"
output:
pdf_document:
keep_tex: true
header-includes:
- \usepackage{tikz}
---
```{r setup, include=FALSE}Knitr::opts_chunk$set(回声=假)
图书馆(TikzDevice)
选项(tikzDefaultEngine= "xetex")
```{r plot, dev="tikz", external=FALSE}X <- r范数(50)
Y <- r范数(50)
地块(x,y,xlab =“Ö”,ylab =“uü”)
使用此代码,tikzDevice使用1252编码编写TeX文件(绘图),当包含在主LaTeX文档中时,该编码无法工作。因此,Pandoc抛出一个错误。我在Ubuntu下试过了,代码可以工作。我怀疑Windows编码是造成这个问题的原因,但我无法找到解决方案。
源文件(Rmd)采用UTF-8编码.生成的TeX文件(由tikzDevice生成)不在UTF-8编码中.
SessionInfo (视窗):
version R version 3.6.1 (2019-07-05)
os Windows 10 x64
system x86_64, mingw32
ui RStudio
language (EN)
collate German_Germany.1252
ctype German_Germany.1252
tz Europe/Berlin
date 2019-09-04 SessionInfo (Ubuntu):
version R version 3.4.4 (2018-03-15)
os Ubuntu 18.04.3 LTS
system x86_64, linux-gnu
ui X11
language (EN)
collate C.UTF-8
ctype C.UTF-8
tz Europe/Berlin
date 2019-09-04发布于 2019-09-04 14:06:02
我可以复制这种行为。请在https://github.com/daqana/tikzDevice/issues以发行的形式打开。作为一种解决办法,您可以使用
---
title: "test"
author: "test"
date: "Today"
output:
pdf_document:
keep_tex: true
header-includes:
- \usepackage{tikz}
---
```{r setup, include=FALSE}Knitr::opts_chunk$set(回声=假)
图书馆(TikzDevice)
选项(tikzDefaultEngine= "xetex")
```{r plot, dev="tikz", external=FALSE}X <- r范数(50)
Y <- r范数(50)
图(x,y,xlab =‘\\“O\”A\“U’,ylab =‘\’o\\”a\“u‘)
发布于 2019-09-04 14:44:05
另一个解决方法是转换图形文件夹中的所有tikz/tex文件。使用iconv,文件内容将从CP1252转换为UTF-8。如果这是文档中的最后一个块,则不需要对Umlauts进行“硬编码”:
# path of the Rmd file
path <- getwd()
# subfolder of the cache and figures
subfolder <- paste(gsub(knitr::current_input(), pattern = ".Rmd", replacement = ""), "_files", sep = "")
# beamer or latex figures
figures <- ifelse(dir.exists(paste(path, subfolder, "figure-latex", sep = "/")), "figure-latex", ifelse(dir.exists(paste(path, subfolder, "figure-beamer", sep = "/")), "figure-beamer", ""))
# full path of the figure folder
folder <- paste(path, subfolder, figures, sep = "/")
# find all tex/tikz files in the figures folder
for (x in list.files(folder, pattern = "*.tex")) {
# full path to file
file <- paste(folder, "/", x, sep = "")
# full path to temp file
temp <- paste(folder, "/", "temp.tex", sep = "")
# rename source file to temp
file.rename(file, temp)
# read input file in correct encoding
input <- readLines(temp, encoding = "cp1252")
# convert input to UTF-8
output <- iconv(input, from = "cp1252", to = "UTF8")
# write output with original filename
writeLines(input, con = file(file, encoding = "UTF8"))
# remove temp file
file.remove(temp)
rm(input, output)
}编辑:现在也可以与beamer一起使用。
发布于 2019-09-04 10:03:55
在R或Python中,当读取CSV或文本文件时,请使用( r'‘)示例r’c:\hem\dow\tra.csv‘,我们必须声明r’‘来读取文件。
https://stackoverflow.com/questions/57785529
复制相似问题