Calling R Script from Python Using Rpy2

Calling R script from python using rpy2

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.

Calling nested R script from python using rpy2

Your func1.R script:

#define function1 here:
func1 <- function(c, d){
}

Your func2.R script:

#define function 2 that uses function1

source("func1.R")
func2 <- function(a,b){
compute c and d here somehow
e <- func2(c,d)
return e
}

Your python code:

import rpy2.robjects as robjects    
def func3(a , b):
path = 'path_to/R_files/'
ro = robjects.r
ro.source(path + "func2.R")
return ro.func3(robjects.FloatVector(a),robjects.FloatVector(b))

Just run a single R command from rpy2 (not a source file)

You can run r commands by using robjects.r from rpy2

from rpy2 import robjects

robjects.r('a=3+5')

#To save the output
r_result=robjects.r('a=3+5')
print(r_result[0])

8.0


Related Topics



Leave a reply



Submit