问题
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