'Is there any way to call base python function in r using reticulate?
I got a "generator object" from a python function. However, I tried many ways but failed to read the "generator object" in r using reticulate. I know python base function list() can convert "generator object" to "json", which I can then read in r. I wonder how to use base python function in r? (I would not prefer to use py_run_file)
For example:
>library(reticulate)
>foo <- import("foo")
>res <- foo.func()
<generator object at 0x7fd4fe98ee40>
Thank you!
Solution 1:[1]
I'm not sure if you can in R directly, but you definitely can in R Markdown. I use R Markdown to flip objects back and forth between the two.
I use a basic html_document YAML output. However, I don't typically knit this type of RMD, so I don't think it really matters what you put there if you use it the same way.
When you use reticulate you need an environment.
So first I'll have an R chunk:
```{r setup}
library(tidyverse) # for random r object creation to use in Python
library(reticulate)
use_virtualenv("KerasEnv") # this is an environment I already have setup
# creating R objects to use with Python
str(diamonds)
cut <- diamonds$cut %>% unique()
```
Then I'll create my Python chunk.
```{r usingPy,results="asis",engine="python"}
import numpy as np
import random
diamonds_py = r.diamonds # bring dataset into Python
mxX = max(diamonds_py.x) # create a new Python object to bring into R
print(mxX)
# 10.74
cut_py = r.cut # bring vector into Python
```
Now let's say I want to bring something from Python back into R.
```{r tellMeMore}
# bring Python object into R
mxX_r = py $ mxX
# [1] 10.74
```
You can run the Python and R code line by line, by chunk, or knit. To clear the Python environment, I'm pretty sure you have to restart RStudio.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kat |
