网状 python 引擎 - 使用 r 作为多个块之间共享的 Python 对象的名称
reticulate python engine - Use r as a name for Python object shared between multiple chunks
我正在使用 {reticulate} 的 Python 引擎编写 R Markdown 文档。我对它的工作方式很满意。
唯一的问题是,我不能使用 r
作为我将在多个块中使用的 Python 对象名称。
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
r = 10
print(r) ##> 10
```
```{python}
print(r) ##> <__main__.R object at 0x119ad37d0>
```
我知道当我们在 Python 块中使用 R 对象时,r
是一个好名字。因为我知道我不会在我的项目中这样做,所以我想使用 r
作为我的 Python 对象的名称。
有什么方法可以更改由 reticulate 创建的 R
对象的名称 r
?或者,告诉 reticulate 不要创建 r
对象?
我知道两个简单的解决方法
- 不要对 Python 个对象使用
r
。
- 将所有内容写成一个大块,不在 Python 个块之间共享
r
。
但我想有更多的自由。
对象名r
是特殊的,因为它用于R和python之间的通信。 R:
中的 py
也是如此
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
foo = 10
print(foo) ##> 10
```
```{r}
library(reticulate)
py$foo ##> [1] 10
```
```{r}
foo <- 10
```
```{python}
print(foo) ##> 10
print(r.foo) ##> 10.0
```
因此,避免使用 r
作为对象名称是我能看到的唯一好的可能性。
仍在研究细节,但我认为设置源和输出编织钩子可能会有所帮助。我肮脏的第一次尝试是这样的:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
knitr::knit_hooks$set(
source = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
sprintf('<div class="%s"><pre class="knitr %s">%s</pre></div>\n', "source", tolower(options$engine), x)
},
output = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
paste0('<pre><code>', x, '</code></pre>\n')
}
)
```
```{python, rsub='rrr'}
rrr = 10
print(rrr)
```
```{python, rsub='rrr'}
print(rrr)
```
我正在使用 {reticulate} 的 Python 引擎编写 R Markdown 文档。我对它的工作方式很满意。
唯一的问题是,我不能使用 r
作为我将在多个块中使用的 Python 对象名称。
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
r = 10
print(r) ##> 10
```
```{python}
print(r) ##> <__main__.R object at 0x119ad37d0>
```
我知道当我们在 Python 块中使用 R 对象时,r
是一个好名字。因为我知道我不会在我的项目中这样做,所以我想使用 r
作为我的 Python 对象的名称。
有什么方法可以更改由 reticulate 创建的 R
对象的名称 r
?或者,告诉 reticulate 不要创建 r
对象?
我知道两个简单的解决方法
- 不要对 Python 个对象使用
r
。 - 将所有内容写成一个大块,不在 Python 个块之间共享
r
。
但我想有更多的自由。
对象名r
是特殊的,因为它用于R和python之间的通信。 R:
py
也是如此
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
foo = 10
print(foo) ##> 10
```
```{r}
library(reticulate)
py$foo ##> [1] 10
```
```{r}
foo <- 10
```
```{python}
print(foo) ##> 10
print(r.foo) ##> 10.0
```
因此,避免使用 r
作为对象名称是我能看到的唯一好的可能性。
仍在研究细节,但我认为设置源和输出编织钩子可能会有所帮助。我肮脏的第一次尝试是这样的:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
knitr::knit_hooks$set(
source = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
sprintf('<div class="%s"><pre class="knitr %s">%s</pre></div>\n', "source", tolower(options$engine), x)
},
output = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
paste0('<pre><code>', x, '</code></pre>\n')
}
)
```
```{python, rsub='rrr'}
rrr = 10
print(rrr)
```
```{python, rsub='rrr'}
print(rrr)
```