use*_*531 6 python r pdflatex knitr r-markdown
在R Markdown中,我可以在R代码块中设置一个对象,然后在我的文档正文中具有该对象的值,如下所示:
```{r}
TMP<-"Blue"
TMP
```
The sky is `r TMP`
Run Code Online (Sandbox Code Playgroud)
我编译的PDF文档中的输出如下所示:
TMP<-"Blue"
TMP
## [1] "Blue"
The sky is Blue
Run Code Online (Sandbox Code Playgroud)
此功能非常有用.但是,我不想仅限于使用R代码.我希望能够使用其他语言在代码块中设置对象,然后以相同的方式在文本中调用它们的值.
RMarkdown + knitr很好地允许你用其他语言编写和编译这些代码块,但是我没有找到任何方法在我的文档文本中调用这些对象的值,就像在RMarkdown中使用这种格式一样来自LaTeX的\ Sexpr {}函数.如果它更容易,我愿意使用不同的文档系统来实现这一目标.我已经看到了这样的问题这样,但是这根本就不是有用,因为我将使用的脚本是更长的时间,比小单行这样的更复杂.
这是一个完整的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`
Run Code Online (Sandbox Code Playgroud)
无需更改或扩展内联代码分隔符来解释多种语言,而是使用网状结构调用 Python 形式 R 并将结果返回给 R 对象。
如下修改 .rmd 文件。确保使用您要使用的 python 版本的正确路径。关于这个 rmd 文件需要注意的是,所有内容都是通过 R 计算的。Python 代码是通过 计算的py_run_string,结果通过调用返回到 R 环境py_to_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`
Run Code Online (Sandbox Code Playgroud)
生成的 PDF 如下所示: