2

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...

Gioelelm
  • 2,645
  • 5
  • 30
  • 49

2 Answers2

3

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

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)
lgautier
  • 11,363
  • 29
  • 42