Skip to content

Instantly share code, notes, and snippets.

@lawsofthought
Created December 29, 2017 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lawsofthought/7da90c515439b02ec8ff006ae70f6c90 to your computer and use it in GitHub Desktop.
Save lawsofthought/7da90c515439b02ec8ff006ae70f6c90 to your computer and use it in GitHub Desktop.
A RMarkdown example illustrating the limitations of Python code in RMarkdown documents
---
title: "Python code chunks in RMarkdown"
author: "Mark Andrews"
date: "29 December 2017"
output: pdf_document
---
Python and R code chunks in RMarkdown do not work the same. The R code chunks are all interpreted in one global environment, but the Python chunks are interpreted in independent environments. Also, I don't think there is any way to have Python inline code.
The following chunks try to illustrate this.
## Chunk 1
```{r}
x <- 42
print(x)
```
## Chunk 2
In the following chunk, the value of `x` on the right hand side is `r x`, which is defined by the previous chunk.
```{r}
x <- x + 12
print(x)
```
## Chunk 3: A Python chunk
This works fine and as expected.
```{python}
x = 42
print(x)
```
But notice that the value of `x` is `r x`, as defined by the last R chunk. As far as I can tell, there is no way to have Python inline code.
## Chunk 4: More Python
The following chunk, if it were uncommented, does not work at all. This is because the Python chunk, unlike the R chunks, are interpreted independently of each other. So if the the following chunk were uncommented, when it gets to the first statement, it raises an error because `x` is not defined. In other words, it does not use the `x` defined in the previous chunk. If you uncomment it, you'll get an error that says `NameError: name 'x' is not defined`.
```{python}
#x = x + 12
#print(x)
```
@yihui
Copy link

yihui commented Dec 30, 2017

Update your R packages, install reticulate, and try this:

---
title: "Python code chunks in R Markdown"
author: "Yihui Xie"
date: "29 December 2017"
output: html_document
---

## Chunk 1

```{r}
library(reticulate)
x <- 42
print(x)
```

## Chunk 2

In the following chunk, the value of `x` on the right hand side is `r x`, which is defined by the previous chunk.
```{r}
x <- x + 12
print(x)
```

## Chunk 3: A Python chunk

This works fine and as expected. 
```{python}
x = 42 * 2
print(x) 
```

The value of `x` in the Python session is `r py$x`. 

## Chunk 4: More Python 

```{python}
x = x + 18 
print(x)
```

Retrieve the value of `x` from the Python session again:

```{r}
py$x
```

Assign to a variable in the Python session from R:

```{r}
py$y <- 1:5
```

See the value of `y` in the Python session:

```{python}
print(y)
```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment