13

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 ?

2
  • Why do you define myfunc here? Commented Mar 14, 2013 at 20:51
  • @agstudy: just an example showing that the file can contain several functions, I think. Commented Mar 15, 2013 at 14:09

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

7 Comments

SignatureTranslatedAnonymousPackage The name is a little bit long I think..for R and python develoopers:)
Yes, may be on the Java extravaganza end of the naming spectrum but still under 140 characters ;-). A shorter class name while keeping it clear would mean introducing a subpackage. Suggestions for names are also welcome.
Of course I came from the .net world and I know what you mean. rpy2 is a great work. I appreciate. +1.. long name but clean solution! I think you can just add import SignatureTranslatedAnonymousPackage as STAP for example...
@agstudy: I edited the code snippet; now the real class name is written only once
string = ''.join(f.readlines()) will give errors. What you should do for R version 3.2.0 (at the time or writing) is like this string = f.read().replace('\n', '')
|
11

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()

1 Comment

This still worked for me in 2016 with R-3.2.2 and rpy2=2.7.0 :)
2

I'd suggest to use what user3282437 suggested here:

import rpy2.robjects as robjects
r_source = robjects.r['source']
r_source('/path_to_file/myfunc.R')
r_getname = robjects.globalenv['getname']

I'm not sure that it's a global issue, but on my Windows machine direct call like agstudy advised:

import rpy2.robjects as robjects
robjects.r('source("some_file.R")')

leads to python crash.

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.