gpt4 book ai didi

python - 相当于 knitr + RMarkdown 中的 Python 等的\Sexpr{}?

转载 作者:行者123 更新时间:2023-12-03 14:50:50 25 4
gpt4 key购买 nike

在 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从 R 调用 Python 并将结果返回给 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 如下所示:

enter image description here

关于python - 相当于 knitr + RMarkdown 中的 Python 等的\Sexpr{}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32697252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com