Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run R script in python using rpy2

Tags:

python

r

rpy2

My question seems very basic but I don't find an answer even on rpy2 documentation. I have *.R script that accept one argument as "file.txt" (I need to pass the argument not from the command line). I want to call the R script inside a python script . My questions is: How to pass and recuperate the arguments to the R script ? My solution is : suppose that the R script is start by this line:

df <- read.table(args[1], header=FALSE)
"
 here args[1] should be the file which is not passed from the command line
"
....

Now I write a function in my python script:

from rpy2 import robjects as ro
def run_R(file):
    r = ro.r
    r.source("myR_script.R")
   # how to pass the file argument to
   # the R script and how to
   # recuperate this argument in the R code?
like image 305
LearnToGrow Avatar asked Apr 25 '19 03:04

LearnToGrow


People also ask

How do I run an R code in Python?

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.

Can you run R packages in Python?

Installing packages Downloading and installing R packages is usually performed by fetching R packages from a package repository and installing them locally. Capabilities to do this are provided by R libraries, and when in Python we can simply use them using rpy2. An interface to the R features is provided in rpy2.

Do I need to install R to use 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.


1 Answers

Why use rpy2 simply to run an R script? Consider avoiding this interface and instead use the automated Rscript.exe command line which Python can call with built-in subprocess like any external executable even while passing needed arguments.

Below assumes you have your R bin folder in the PATH environment variable to recognize Rscript. If not, add full path of this executable in first arg of cmd. Also, be sure to pass full path of file into run_R method:

from subprocess import Popen, PIPE

def run_R(file):
  # COMMAND WITH ARGUMENTS
  cmd = ["Rscript", "myR_script.R", file]

  p = Popen(cmd, cwd="/path/to/folder/of/my_script.R/"      
            stdin=PIPE, stdout=PIPE, stderr=PIPE)     
  output, error = p.communicate()

  # PRINT R CONSOLE OUTPUT (ERROR OR NOT)
  if p.returncode == 0:            
      print('R OUTPUT:\n {0}'.format(output))            
  else:                
      print('R ERROR:\n {0}'.format(error))
like image 66
Parfait Avatar answered Sep 24 '22 00:09

Parfait