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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With