Using an R-script in python that was written for R

A friend has some R scripts that may be useful. But I use Python, and when it updates its scripts, I want to use its updates.

Can i embed as-is R scripts in Python?

A typical R-script that he can write is called, for example, quadro.R and looks like:

quadro <- function(x) {
  return(x*x)}

Is there any way to call quadro.R from python with argument "3" and get the result "9" in Python? I have R installed on my Linux system.

As I understand rpy / rpy2 , can I use R commands in python but not use R script, or am I misunderstood something? Is there any other way to use R-script from Python?

+4
source share
2 answers

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

Python script example,

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
+3
source

Rpy2 makes good use of this kind of use, I think. You can encapsulate free R-scripts in packages (and avoid storing objects in the global R environment), which should be as carefully considered as using global variables in Python).

import rpy2.robjects.packages.SignatureTranslatedAnonymousPackage as STAP

with open('quadro.R') as fh:
    rcode = fh.read()
quadro = STAP(rcode, 'quadro')

# The function is now at
quadro.quadro()
# other functions or objects defined in that R script will also be there, for example
# as quadro.foo()

This is in the rpy2 documentation .

0
source

All Articles