Can R variables be passed to py_run_string in reticulate package?

I was wondering if there is a way to pass R variables into py_run_string in reticulate? I saw that it is easy to do in RMarkdown using the notation r.variablename. But I was also interested in knowing whether that is possible when working directly in a R script instead of Rmarkdown. I have listed below example code to illustrate what I am trying to do.

py_run_string("x = 10")

py$x # gives the value 10

# for passing a R variable into python, currently I define a function
def getsquare(y):
    return y**2

y  = 10
py$getsquare(y) # gives the value 100

# My question is whether there is an easier way to pass y into py_run_string something like

I would appreciate any pointers on this.

I am apprehensive about interpolating into strings then executing the result, due to the possibility of injection attacks.

Assuming that you are managing this risk, you might consider the glue package.


y = 10

1 Like

Thanks very much for your suggestion and the note of caution on using this. I was not familiar with glue package. Seems like a good one to know for other tasks also.

1 Like