使用 knitr/rmarkdown 以多种自然语言生成输出(来自 data.frame)

using knitr/rmarkdown to produce outputs in multiple natural languages (from a data.frame)

我正在尝试在 rmarkdown 中生成一个文档,它可以生成多种(自然)语言的输出,它应该从 data.frame 中提取其中一种翻译中的文本。

data.frame 应包含每种语言的列和每行相同文本的翻译,例如

EN <- c('title', 'author', 'a sentence')
FR <- c('titre', 'auteur', 'une phrase')
translation <- data.frame(EN, FR, stringsAsFactors = FALSE)

应该可以对提取的文本进行格式化,例如

# [desired code here]

应该生成 rmarkdown 标题。

编辑:理想情况下,我们可以在 YAML front-matter

中指定语言

当你在这里提出问题时,我也将我的答案添加给你。您可以在块中使用 catresults='asis',并将您的 table 翻译语言与格式化块的内容进行比较。
这样,原始文本在块中(在 rstudio 中)突出显示,以便您可以轻松地在长代码中找到您的文本。使用内联Rcode,一切都是相同的颜色,这不容易看到。

```{r TransRef}
# Translation reference
tr.orig <- translation[,"EN"]
```


```{r MyFirstParagraph, results='asis', verbatim=TRUE}
cat('
# ', translation[tr.orig == "title", lang], '

', translation[tr.orig == "a sentence", lang], '   

- ', translation[tr.orig == "author", lang], '
', sep = "")
```

您可以按如下方式执行此操作:(请参阅 ps 了解更多 latex-options)

为什么? YAML header 逐行评估 :) - 请参阅 here

---
params:
  lang: EN
lang: "`r switch(params$lang, DE = 'de-DE', EN = 'en-US')`"
output: pdf_document
toc: 1
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
lswitch <- function(lang, ...){
  switch(lang, ..., stop("No translation privided"))
}
```

# `r lswitch(params$lang, DE = "Dies ist der Titel", EN = "this is the title")`

`r lswitch(params$lang, 
DE = "Die folgende Abbildung zeigt die Funktion $f(x) = x^2$", 
EN = "The following plot shows the function $f(x) = x^2$"
)
`

```{r plot1_cap, include=FALSE}
plot1_cap <- lswitch(params$lang, DE = "Tolle Abbildung", EN = "Great plot")
```
```{r plot1, fig.cap= plot1_cap}
plot(seq(-5, 5, length.out = 50), seq(-5, 5, length.out = 50)^2, 
     type = "l", xlab = "x", ylab = "f(x)")
```

# `r lswitch(params$lang, DE = "Zweiter Titel", EN = "Second Title")`

`r lswitch(params$lang, 
DE = "Zweiter Abschnitt", 
EN = "Second paragraph"
)
`

这导致

如果将 yaml-header 更改为

---
params:
  lang: DE
lang: "`r switch(params$lang, DE = 'de-DE', EN = 'en-US')`"
output: pdf_document
toc: 1
---

你得到

PS:更多 Latex 选项

如果您想使用特定的语言包,您可以在 YAML header 中添加以下内容:(参见 https://whosebug.com/a/29163496/3301344

---
header-includes:
  - \usepackage[ngerman]{babel}
---

例如用中文看看:http://felixfan.github.io/RMarkdown-Chinese-PDF/