问题
I am trying to add a python chunk in a rmarkdown document. I installed package reticulate then here is my document:
```{r, message=FALSE, warning=FALSE, echo = FALSE}
library(reticulate)
```
```{python, echo = FALSE, eval = FALSE}
a=1
a
#import numpy as np
#import matplotlib.pyplot as plt
## evenly sampled time at 200ms intervals
#t = np.arange(0., 5., 0.2)
## red dashes, blue squares and green triangles
#plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
#plt.show()
```
However I get this error when knitting the document: (note that the error happens when running the second chunk)
label: unnamed-chunk-1 (with options)
List of 3
$ message: logi FALSE
$ warning: logi FALSE
$ echo : logi FALSE
|
|.... | 6%
ordinary text without R code
|
|...... | 9%
label: unnamed-chunk-2 (with options)
List of 3
$ echo : logi FALSE
$ eval : logi FALSE
$ engine: chr "python"
Error in py_module_import(module, convert = convert) :
ModuleNotFoundError: No module named 'rpytools'
Calls: <Anonymous> ... remap_output_streams -> import -> py_module_import -> .Call
Also adding that I did not find any information on this on https://github.com/rstudio/reticulate and https://rstudio.github.io/reticulate/articles/r_markdown.html
I have knitr version 1.20, which is above 1.18 hence engine configuration should be automatic.
回答1:
This is likely caused by using an RStudio version lower than 1.2. It's well-hidden on the reticulate
pages, but actually some aspects of importing Python packages and running Python chunks seem to be supported only in RStudio version 1.2 and up — that is, not the current RStudio stable release, but the preview that you have to download and install separately.
Here's what they write in the vignette:
Note that the RStudio v1.2 preview release includes support for using reticulate to execute Python chunks within R Notebooks. See the RStudio IDE Tools for reticulate article for additional details.
Probably because of this, when running your code in RStudio 1.1.53, I get "ModuleNotFound" errors like you do, and they prevent knitting.
When running it in the RStudio 1.2.1139 preview release, all is as it should be:
Reticulate 1.10 REPL -- A Python interpreter in R.
>>> a=1
>>> a
1
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> ## evenly sampled time at 200ms intervals
>>> t = np.arange(0., 5., 0.2)
>>>
>>> ## red dashes, blue squares and green triangles
>>> plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
[<matplotlib.lines.Line2D object at 0x000000001C2EDBE0>, <matplotlib.lines.Line2D object at 0x000000001DA99978>, <matplotlib.lines.Line2D object at 0x000000001DA99D30>]
>>> plt.show()
>>> plt.savefig("test.png")
>>>
来源:https://stackoverflow.com/questions/50562069/python-in-rmarkdown-reticulate