Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a python variable persist between chunks in a markdown notebook?

Variable are not retained from one chunk to the next in notebook mode, but they are retained when knitting the markdown document to html.

I made a sample document available as a gist called pythonvariables.Rmd, the content of this file is:

---
title: "R Notebook"
output:
  html_document:
    df_print: paged
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(reticulate)
```

```{python}
x = 1 
```

```{python}
print(x)
```

```{r}
print(py$x)
```

In Rstudio version 1.1.453, in notebook mode, when running one chunk after the other, the output of the print(x) python chunk is:

Traceback (most recent call last):
  File "C:\Users\rougipa\AppData\Local\Temp\2\RtmpQFW3Rj\chunk-code-1d44920f50.txt", line 1, in <module>
    print(x)
NameError: name 'x' is not defined

However the issue doesn't appear when the Rmd is compiled to html. The output of the print(x) python chunk is 1 as expected.

like image 960
Paul Rougieux Avatar asked Oct 17 '22 16:10

Paul Rougieux


1 Answers

This functionality works in Rstudio preview 1.2.747. Question kept for historical purposes.

like image 131
Paul Rougieux Avatar answered Nov 01 '22 11:11

Paul Rougieux