Wrap R function in python

随声附和 提交于 2019-12-11 02:54:17

问题


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)

I guess I have to use rpy directly, I am not sure how...


回答1:


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



回答2:


Whenever a function is in an R package, you can use importr:

from rpy2.robjects.packages import importr
princurve = importr('princurve')

princurve.principal_curve(X)


来源:https://stackoverflow.com/questions/25217997/wrap-r-function-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!