0

I am writing an R Markdown document using the Python engine of {reticulate}. I am quite happy with how it works.

The only thing is, I cannot use r as a Python object name that I'm going to use in multiple chunks.

---
title: "Untitled"
output: html_document
---

## Object name `r`

```{python}
r = 10
print(r)  ##> 10
```

```{python}
print(r)  ##> <__main__.R object at 0x119ad37d0>
```

I understand r is a good name when we use R objects from within a Python chunk. Since I know I am not going to do that in my project, I would like to use r as a name for my Python object.

Is there any way to change the name, r, for the R object created by reticulate? Or, to tell reticulate not to create r object?

I am aware of the two straightforward workarounds

  1. Don't use r for Python objects.
  2. Write everything in one big chunk and not share r between Python chunks.

but I'd like to have more freedom.

Kenji
  • 227
  • 1
  • 10

2 Answers2

0

The object name r is special since it is used to communicate between R and python. The same holds for py in R:

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

Avoiding the use of r as an opject name is therefore the only good possibility I can see.

Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75
  • It's a shame... I had the same impression when I saw "r = R()" hard-coded in the source code... although I don't quite understand most of it. https://github.com/rstudio/reticulate/blob/0ad258495b95cf026488314f62a6bb8fdae41f76/R/python.R#L1403 But I thank you for your reply! – Kenji Aug 02 '19 at 02:04
  • I have decided to work around this issue (at least to me) by defining a custom knit_hook option that I set with a temporary variable name like `rrr`. And the temp variable name is replaced with desired `r` in source and output code, after execution. This seems to be enough for me. – Kenji Sep 12 '19 at 00:22
  • @Kenji Interesting. How about adding it as an answer? – Ralf Stubner Sep 12 '19 at 05:50
0

Still working on the details but I think setting source and output knit hooks may help. My dirty first try looks like this:

---
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)
```
Kenji
  • 227
  • 1
  • 10