Created
December 29, 2017 22:05
-
-
Save lawsofthought/7da90c515439b02ec8ff006ae70f6c90 to your computer and use it in GitHub Desktop.
A RMarkdown example illustrating the limitations of Python code in RMarkdown documents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
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) | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update your R packages, install reticulate, and try this: