How to make a python variable persist between chunk in a markdown notebook?
How to make a python variable persist between chunk 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:
print(x)
Traceback (most recent call last):
File "C:UsersrougipaAppDataLocalTemp2RtmpQFW3Rjchunk-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.
print(x)
Gists can disappear or change over time, could you include the (current) source of the Rmarkdown document to keep this question self-sufficient?
– r2evans
Jun 27 at 14:34
If a question is related to RStudio, please state its version. Without that information, a blind guess is that the latest (preview) version might have fixed your problem: rstudio.com/products/rstudio/download/preview
– Yihui Xie
Jun 28 at 15:00
1 Answer
1
This functionality works in Rstudio preview 1.2.747. Question kept for historical purposes.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It's related to the third comment by pjcrosbie in this knitr bug request: Python environment persistance across chunks #1440.
– Paul Rougieux
Jun 27 at 14:11