本文介绍了在Python中包装R函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想包装包含在princurve包中的R函数.使用ipython,我可以使用ipython cell R magic成功做到这一点:
I would like to wrap a R function contained in a package princurve.With ipython I do it successfully with an ipython cell R magic:
%%R -i X -o s,lambda
fit1<-principal.curve(X)
s <- fit1$s
l <- fit1$lambda
但是我想要一个可以从以下模块导入的函数:
but I want a function that I can import from a module like:
from mymodule import principal_curve
s, l = principal_curve(X)
我想我必须直接使用rpy,我不确定如何...
I guess I have to use rpy directly, I am not sure how...
推荐答案
我不使用R,而是在文档,您可以定义一个函数并将其导入python模块:
I don't use R but using this example in the docs you can define a function and import it into a python module:
r_mod.py
from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage
string = """
square <- function(x) {
return(x^2)
}
cube <- function(x) {
return(x^3)
}
"""
powerpack = SignatureTranslatedAnonymousPackage(string, "powerpack")
py_mod.py
from r_mod import powerpack
print powerpack.square(3)
[1] 9
这篇关于在Python中包装R函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!