Using an R-script in python, which was written for R

python, r

Solution

First load the whole R script in python, then get any of its R object (function, variable, etc.) assigned and called in python.

An example python script,

from rpy2 import robjects

robjects.r('''                         
source('quadro.R')
''')                                   #load the R script

quadro = robjects.globalenv['quadro']  #assign an R function in python
quadro(3)                              #to call in python, which returns a list
quadro(3)[0]                           #to get the first element: 9

Problem

A friend has some R-scripts that I might find useful. But I use Python, and when he upgrades his scripts I want to be able to use his updates. Is it possible to embed R-scripts as-is in Python? An typical R-script he might write is named e.g. quadro.R and has the form: ``` quadro <- function(x) { return(x*x)} ``` Can I somehow call quadro.R from python with the argument "3" and get the result "9" back in Python? I do have R installed on my Linux system. As I understand rpy/rpy2, I can use R-commands in python but not use an R-script, or did I misunderstood something? Is there some other way to use an R-script from within Python?

Original source