2

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)
2
  • Can you add to the question the python version you are using? Commented Jul 16, 2021 at 9:00
  • Hi @Letsamrit, I have conducted further testing and research and have made sure my answer answers everything, and I hope it helps Commented Jul 19, 2021 at 7:56

1 Answer 1

1
+50

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
Sign up to request clarification or add additional context in comments.

2 Comments

would you please show me how to adapt the code to pass array of integers ?
You can also encapsulate the code in the R source file in a namespace. See rpy2.github.io/doc/v3.4.x/html/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.