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
In Python, How to Read the Exif Data for an Image
Apt-Get Install for Different Python Versions
Importerror: Libcblas.So.3: Cannot Open Shared Object File: No Such File or Directory
Show Default Value for Editing on Python Input Possible
Combine Several Images Horizontally with Python
Transpose Column to Row with Spark
How to Find Length of Digits in an Integer
Removing Duplicate Characters from a String
Syntaxerror: Non-Ascii Character '\Xa3' in File When Function Returns '£'
Id' Is a Bad Variable Name in Python
How to Replace Text in a String Column of a Pandas Dataframe
Running a Linux Command from Python
Circular Shift of Vector (Equivalent to Numpy.Roll)
How to Postpone/Defer the Evaluation of F-Strings
Case Insensitive Regular Expression Without Re.Compile
How to Get a Value of Datetime.Today() in Python That Is "Timezone Aware"