How to pass integer arguments to R-script from python

Viewed 321

i have the below posted R-code and i want to pass the parameter nfrom python code and display the results. that is, if i passed 4 then 16 must be printed out on the screen. please let me know how to pass argumnets to R-script from python

R-Code:

Square <- function(n) {
return(n^2)
}

Python-code:

command ='Rscript'
path2Func1Script ='/var/www/aw/Rcodes/func-1.R'
args = [3]
cmd = [command, path2Func1Script]

output = None
try:
    x = subprocess.call(cmd + args, shell=True)
    print("x: ", x)
except subprocess.CalledProcessError as e:
    output = e.output
    print("output: ", output)
1 Answers

Solution:

I see you are doing this manually may I suggest you use an awesome python library built for this called rpy2. Rpy2 provides a lot of functionality to use R libraries and functions from python itself without having to manually call the r script in a command line argument from python using subprocess, and this not only makes it easier to code but is more efficient.

The most important thing to note is that to parse a python integer list to an r function you need to convert it to an r IntVector like so robjects.vectors.IntVector().Another thing to mention is you need to set your R_HOME environment variable to the path of your R installation if you are using windows

Firstly install rpy2 by using conda(pip only works on linux with this package):

conda install -c conda-forge rpy2

Here is the code python code:

import rpy2.robjects as robjects


# Defining the R script and loading the instance in Python
r = robjects.r
r['source']('func-1.R')

# Loading the function we have defined in R.
square_func = robjects.globalenv['Square']

# defining the args
args = robjects.vectors.IntVector([3])

#Invoking the R function and getting the result
result_r = square_func(args)

#printing it.
print('x: ' , result_r)

Output:

x: [1] 9
Related