Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr - Python engine cache option not working

yihui gives an example of using the cache option for the different engines

https://github.com/yihui/knitr-examples/blob/master/023-engine-python.Rmd

I can't seem to get it to work for python.

The following works

```{r,engine='python',cache=TRUE}
x=10
print x
```

But this doesn't work

```{r,engine='python',cache=TRUE}
x = 10
```

```{r,engine='python',cache=TRUE}
print x
```

Anyone have an idea?

like image 216
Glen Thompson Avatar asked May 11 '15 19:05

Glen Thompson


People also ask

How do I clear my knitr cache?

If you run into problems with cached output you can always clear the knitr cache by removing the folder named with a _cache suffix within your document's directory.

How do I use cache in R Markdown?

R Markdown has a built-in caching feature that can be enabled by setting cache=TRUE in the chunk's header. The second time the chunk is run, both the visual output and any objects created are loaded from disk.

How do I run Python code in R Markdown?

To add a Python code chunk to an R Markdown document, you can use the chunk header ```{python} , e.g., ```{python} print("Hello Python!") ```

What is the equivalent of R Markdown in Python?

The reticulate package includes a Python engine for R Markdown that enables easy interoperability between Python and R chunks. Python chunks behave very similar to R chunks (including graphical output from matplotlib) and the two languages have full access each other's objects.


1 Answers

The chunk option cache doesn't save all the variables defined in the block for languages other than R. It is, though, saving printed outputs, so if you compute something that takes a while, any results will not need to be re-computed. From the knitr website:

Except engine='R' (default), all chunks are executed in separate sessions, so the variables cannot be directly shared. If we want to make use of objects created in previous chunks, we usually have to write them to files (as side effects). For the bash engine, we can use Sys.setenv() to export variables from R to bash (example).

It's possible to save a few values in the shell's environment, and retrieve those values from the other cells by reading the environment. This is the approach Yihui took in the Polyglot example. So, for Python, if you can format the value as a string and pass it to sys.setenv(), you could use that value in another cell (run as a separate Python session) by calling sys.getenv().

Though, I am mildly confused about the approach taken with the C and Fortran engines. Those seem to have access to compiled functions in later chunks by using some function called .C() or a function called .Fortran(). But it seems that Python does not have an equivalent.

like image 191
pneumatics Avatar answered Sep 30 '22 06:09

pneumatics