Running R Script from Python

Running R script in Python

Your variable output will only store the output from the source file, which is exactly what you get, id est the last variable. But all the variables actually live somewhere, in an R environment, which you can get with robjects.globalenv.
Knowing that you can easily retrieve the value for each variable that you created in R:

import rpy2.robjects as robjects
robjects.r.source("sample.R")
print(robjects.globalenv["a"])
print(robjects.globalenv["b"])
print(robjects.globalenv["c"])
print(robjects.globalenv["data"])

Problem running a R script from Python (Windows)

Use double backslashes.

In R you need to use double backslashes \\, otherwise it'll try to interpret it as an Escape Character.

Use this and it will work:

os.system("C:\\R-3.6.1\\bin\\Rscript run.R")

Hope this helps.

How do I call a Python variable from an R script in RStudio

You can do it using the reticulate package:

Python_script.py (run in R studio):

import numpy as np

x = np.random.rand(100)

quit

r_script.R:

library(reticulate)

py$x
#> [1] 0.144915024 0.824587306 0.781184497 0.442235857 0.848616639
# [6] 0.474798959 0.426096485...

y <- 1:10

Python_script2.py:

r.y
# >>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Or just run reticulate::source_python('Python_script.py') in R



Related Topics



Leave a reply



Submit