简体   繁体   中英

How to run an R function from python with parameters?

myScript.R:

model <- function(data)
{
      Do some stuff
}

Python:

import subprocess
def execution(data):
    exp=subprocess.Popen(["Rscript", "myScript.R"],stdout=subprocess.PIPE, bufsize=-1)
    for line in exp.stdout:
         if line[0:3]=="[1]":
            return line

how do I pass the data parameter to my R function?

Rpy2软件包非常适合这类事情,有关您问题的文档可以在这里找到: https ://rpy2.readthedocs.io/en/version_2.8.x/introduction.html#calling-r-functions

One approach is to use the python package rpy2, available from https://rpy2.bitbucket.io/ with documentation at https://rpy2.readthedocs.io/en/version_2.8.x/

The R package is widely available, either via pip or distribution repositories (including macports and standard linux distributions).

In your case,

from rpy2 import robjects as r
r.r.source('your_r_script.R')

At this stage, the functions contained in your_r_script are loaded in the `rr' object, and you can access them as if you were in R:

output = r.r['your_function_name'](param1, param2, param3)

output will be a so-called r-object, which you will be able to access more or less straightforwardly depending on what it contains.

If it is a list, you access its coefficients with the method rx2 , eg: output.rx2(1) will give you the first element of the list, and output.rx2('param') will give you the element of the list that is called 'param'. If this is an array, you use the method rx .

Again, see the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM