31

I'm very new to rpy2, as well as R.

I basically have a R script, script.R, which contains functions, such as rfunc(folder). It is located in the same directory as my python script. I want to call it from Python, and then launch one of its functions. I do not need any output from this R function. I know it must be very basic, but I cannot find examples of R script-calling python codes. What I am currently doing, in Python:

import rpy2.robjects as robjects

def pyFunction(folder):
    #do python stuff 
    r=robjects.r
    r[r.source("script.R")]
    r["rfunc(folder)"]
    #do python stuff

pyFunction(folder)

I am getting an error on the line with source:

r[r.source("script.R")] File "/usr/lib/python2.7/dist-packages/rpy2/robjects/__init__.py", line 226, in __getitem__ res = _globalenv.get(item) TypeError: argument 1 must be string, not ListVector

I quite do not understand how the argument I give it is not a string, and I guess the same problem will then happen on the next line, with folder being a python string, and not a R thingie.

So, how can I properly call my script?

Efferalgan
  • 1,681
  • 1
  • 14
  • 24

1 Answers1

44

source is a r function, which runs a r source file. Therefore in rpy2, we have two ways to call it, either:

import rpy2.robjects as robjects
r = robjects.r
r['source']('script.R')

or

import rpy2.robjects as robjects
r = robjects.r
r.source('script.R')

r[r.source("script.R")] is a wrong way to do it.

Same idea may apply to the next line.

quantif
  • 166
  • 3
  • 12
CT Zhu
  • 52,648
  • 17
  • 120
  • 133
  • I want to launch the rfunc function, defined in script.R, with the argument *folder*, which is given as an argument to my python function. – Efferalgan Jul 03 '14 at 03:21
  • For the next line, `r.rfunc(folder)` works, same way as your solution. It seems I was looking for too complicated things while the solution was extremely simple. Thanks. – Efferalgan Jul 03 '14 at 03:28
  • 1
    Yep, exactly. `r["rfunc(folder)"]` will pass `folder` as a string `'folder'`, which is probably not what you want. I run up of up votes today, I will do that tomorrow. Cheers! – CT Zhu Jul 03 '14 at 03:34