Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Custom functions from Python using rpy2

Tags:

python

r

rpy2

Is there a way to call functions defined in a file say myfunc.r

---------------myfunc.r --------------
myfunc = function(){
  return(c(1,2,3,4,5,6,7,8,9,10))
}

getname = function(){
  return("chart title")
}

---- Python 
   How to call getname() here ?

Any help would be greatly appreciated ?

like image 897
user2171582 Avatar asked Mar 14 '13 20:03

user2171582


People also ask

How do I use rpy2 in Python?

Installing rpy2 You must have Python >=3.7 and R >= 4.0 installed to use rpy2 3.5. 2. Once R is installed, install the rpy2 package by running pip install rpy2 . If you'd like to see where you installed rpy2 on your machine, you can run python -m rpy2.

Does rpy2 work with Python 3?

rpy2 is almost certainly not working with Python 2.6. Older Python versions are even less likely to work. While Python 3.3 should be working, earlier version of Python 3 are not expected to (they might work, they might not - you are on your own). Rpy2 is not expected to work at all with an R version < 2.8.

What is rpy2 in Python?

rpy2 is an interface to R running embedded in a Python process. on Pypi. Questions and issues. Consider having a look at the documentation. Otherwise questions should preferably be asked on the rpy mailing-list on SourceForge, or on StackOverflow.


2 Answers

There are features in rpy2 that should help making this cleaner than dumping objects into the global workspace.

from rpy2.robjects.packages import STAP
# if rpy2 < 2.6.1 do:
# from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage
# STAP = SignatureTranslatedAnonymousPackage
with open('myfunc.r', 'r') as f:
    string = f.read()
myfunc = STAP(string, "myfunc")

The objects in the R file can now be accessed with myfunc.myfunc and myfunc.getname.

Check the documention about importing arbitrary R code as a package.

like image 177
lgautier Avatar answered Oct 19 '22 23:10

lgautier


You can do something like this ( python code here)

import rpy2.robjects as robjects
robjects.r('''
       source('myfunc.r')
''')

 r_getname = robjects.globalenv['getname']

then you call it

r_getname()
like image 45
agstudy Avatar answered Oct 19 '22 23:10

agstudy