0

I have two scripts open in an RStudio environment. One Python_script.py and r_script.R

I want to be able to save a variable in either script and be able to call that variable from the other, in the other language.

Thanks in advance

3
  • 3
    Does this answer your question? Running Python from R
    – BatWannaBe
    Oct 20, 2021 at 11:14
  • 1
    I really really think running two languages that share some variables is just asking for troubles in the near future. If you want to have clean code, that will be easy to maintain, please modify the way your scripts share data, and use something like JSON files or CSV files Oct 20, 2021 at 11:52
  • @Be Chiller Too While I would agree that in my experience, data sharing or data type conversion between two separate interpreters in two different languages is limited and hard to debug, but it can come in handy to quickly borrow another function for a well-supported data type instead of having to write files and swap interpreters.
    – BatWannaBe
    Oct 20, 2021 at 12:59

1 Answer 1

2

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.