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.