Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing R variables to a python script with reticulate

I have a python script that I want to run from within R using the reticulate package. I want to assign some variables in R first, and then pass them to the script. Unfortunately when I run the script, I am surprised to see that python can't recognize the variables. What am I missing here? Thanks

Python script (test.py):

print(x)

R code:

library(reticulate)
x <- 5
source_python(test.py)

The error:

Error in py_run_file_impl(file, local, convert) : 
  NameError: name 'x' is not defined
like image 571
Jacqueline Nolis Avatar asked Oct 21 '25 05:10

Jacqueline Nolis


1 Answers

The solution I came up with was to just create a function. So if before my python code was

z = x + 3

My new python code would be:

def add_three(x):
    z = x + 3
    return z

and then I can, in R run:

x <- 5
source_python("test.py")
y <- add_three(x)

and get y as 6.

like image 157
Jacqueline Nolis Avatar answered Oct 23 '25 19:10

Jacqueline Nolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!