在R Markdown中,我可以在R代码块中设置一个对象,然后在我的文档正文中获得该对象的值,如下所示:
```{r}
TMP<-"Blue"
TMP
```
The sky is `r TMP`
在我编译的PDF文档中,此输出看起来像这样:
TMP<-"Blue"
TMP
## [1] "Blue"
The sky is Blue
此功能非常有用。但是,我不希望局限于R代码。我希望能够使用其他语言在代码块中设置对象,然后以相同的方式在文本中调用它们的值。
RMarkdown + knitr在允许您以其他语言编写和编译这些代码块方面做得很出色,但是我找不到任何以这种格式在文档文本中调用这些对象的值的方法。 RMarkdown或LaTeX的\ Sexpr {}函数都可以。如果比较容易,我愿意使用其他文档系统来完成此操作。我已经看到诸如this之类的问题,但这根本无济于事,因为我将使用的脚本比类似的小单行代码更长,更复杂。
这里是完整的RMarkdown文档,详细介绍了R的当前行为以及Python的期望(相同)行为,等等。
---
title: "SAMPLE"
author: "me"
date: "September 21, 2015"
output:
pdf_document:
keep_tex: yes
---
```{r}
TMP<-"Blue"
TMP
```
You can insert the value of an object created with an R code chunk into text like this:
The sky is `r TMP`
```{r,engine='python'}
COLOR = "red"
print COLOR
```
You cannot do the same thing with Python, or other types of code:
The car is `python COLOR`
而不是试图更改或扩展内联代码定界符以解释多种语言,而是使用reticulate调用Python形式R,并将结果返回给R对象。
如下修改.rmd文件。确保为要使用的python版本使用正确的路径。有关此rmd文件的注意事项是,所有内容都通过R评估。Python代码通过py_run_string
评估,结果通过py_to_r
调用返回到R环境。
---
title: "SAMPLE"
author: "me"
date: "September 21, 2015"
output:
pdf_document:
keep_tex: yes
---
```{r setup}
library(reticulate)
reticulate::use_python(python = "/opt/anaconda3/envs/ten2/bin/python", required = TRUE)
```
```{r}
TMP<-"Blue"
TMP
```
You can insert the value of an object created with an R code chunk into text like this:
The sky is `r TMP`
```{r}
pycode <-
'
COLOR = "red"
print(COLOR)
'
pyrtn <- py_to_r(py_run_string(code = pycode))
```
You cannot do the same thing with Python, or other types of code:
The car is `r pyrtn$COLOR`
生成的PDF看起来像这样: