4

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?

1

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

Rpy2 covers this kind of use rather well, I think. You can encapsulate loose R scripts into packages (and avoid storing objects into R's global environment - something that should be as carefully considered as the use of 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.