[英]How to run an R function from python with parameters?
myScript.R: 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? 如何将data参数传递给R函数?
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/ 一种方法是使用python软件包rpy2,该软件包可从https://rpy2.bitbucket.io/获得,其文档位于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). R软件包可通过pip或分发存储库(包括macports和标准linux分发版)广泛使用。
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: 在这一阶段, your_r_script
中包含的函数被加载到`rr'对象中,并且您可以像在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. output
将是所谓的r对象,您将可以根据其包含的内容直接访问r对象。
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'. 如果是列表,则使用rx2
方法访问其系数,例如: output.rx2(1)
将为您提供列表的第一个元素,而output.rx2('param')
将为您提供列表的元素这就是所谓的“参数”。 If this is an array, you use the method rx
. 如果这是一个数组,则使用方法rx
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.