Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a R function from python code with passing arguments

Tags:

python-3.x

r

rtest = function(input ,output) {
  a <- input
  b <- output 
  outpath <- a+b
  print(a+b)
  return(outpath)
}

I have just return this R code for as a function for getting sum of two numbers. I tried to run this function from my python code using subprocess by passing 2 numbers as arguments. But it does not return sum value as return output. Do you know any method for implement this in python3 by passing function arguments.

my python code using subprocess is:

args=['3','10'] # (i tried to pass aruments like this) 
command="Rscript" 
path2script = '/...path/rtest.R' 
cmd = [command, path2script] +args 
x = subprocess.check_output(cmd, universal_newlines=True) 
print(x)

but x return ' ' null value

like image 911
9113303 Avatar asked May 09 '26 01:05

9113303


1 Answers

This could be easily done by rpy2 library in python.

    import rpy2.robjects as ro
    path="specify/path to/ R file"

        def function1(input,output):
            r=ro.r
            r.source(path+"rtest.R")
            p=r.rtest(input,output)
            return p


  a=function1(12,12)   # calling the function with passing arguments

Thanks.

like image 102
9113303 Avatar answered May 10 '26 19:05

9113303