Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling R script from python using rpy2

Tags:

python

r

call

rpy2

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?

like image 598
Efferalgan Avatar asked Jul 03 '14 02:07

Efferalgan


People also ask

Can I call R script from Python?

Using the Python interface for R With everything set up, you can begin using the Python interface! However, this is not as simple as writing R code in your Jupyter notebook. You have to 'translate' R functions to call them from Python.

Does rpy2 support python3?

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.

Do I need to install R for rpy2?

rpy2 will typically require an R version that is not much older than itself. This means that even if your system has R pre-installed, there is a chance that the version is too old to be compaible with rpy2. At the time of this writing, the latest rpy2 version is 2.8 and requires R 3.2 or higher.

What is rpy2 package?

rpy2 is running an embedded R, providing access to it from Python using R's own C-API through either: a high-level interface making R functions an objects just like Python functions and providing a seamless conversion to numpy and pandas data structures.


1 Answers

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.

like image 96
CT Zhu Avatar answered Oct 11 '22 08:10

CT Zhu