【问题标题】:Equivalent to \Sexpr{} for Python, etc., in knitr + RMarkdown?相当于 knitr + RMarkdown 中的 Python 等的 \Sexpr{}?
【发布时间】:2015-12-18 06:33:13
【问题描述】:

在 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`

【问题讨论】:

  • 恐怕目前knitr 无法实现这一点,因为每个引擎(除了原生 R 引擎)都会启动一个新实例:github.com/yihui/knitr/blob/…github.com/yihui/knitr/blob/…
  • 注意:如果您展示了所需的行为(例如,具有所需输出的示例文件),问题会更清楚。欢迎使用 StackOverflow!
  • 我已将整个示例 RMarkdown 文档包含在原始帖子中。感谢您的快速回复和信息,我之前无法弄清楚。当您说为每个引擎启动一个新实例时,是针对整个文档吗?还是每个代码块?以及如何排除从这些实例调用值/对象以插入文本?我正在考虑将其他语言的输出写入文本文件,并在必要时在 R 块中调用它,尽管它是一个相当不雅的解决方案。谢谢。
  • 每个块的一个新实例。这意味着例如每个 Python 块都会启动一个新的 Python 会话,您需要一些东西来保存状态和/或将其传输到 R 或从 R 传输。我想,正如您所建议的,一个简单的文件接口是您目前可以做的下一个最好的事情。跨度>
  • 目前无法使用 knitr,除非您扩展其 python 引擎,这是可能的,例如github.com/yihui/runr 您必须为内联表达式编写自己的函数,例如get_python_value = function(code) { .... }(在这里填空可能很简单,也可能不太重要)然后在内联 R 表达式中使用get_python_value('your python code')

标签: python r knitr r-markdown pdflatex


【解决方案1】:

不要寻求更改或扩展内联代码分隔符来解释多种语言,而是使用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 如下所示:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-23
    • 2016-10-06
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多