简体   繁体   中英

Passing Python Lambda function to R via rpy2

I would like to write a Python wrapper around the R library Rdtq ( https://github.com/cran/Rdtq ). That library (or rather, the class instance) takes as main inputs two functions: the drift f(x) and diffusion g(x). For instance,

my_drift = function(x) { -x }
my_diff  = function(x) { rep(1,length(x)) }

Since I am writing a wrapper around the Rdtq class, I would like to pass the drift and diffusion function directly from Python, ideally via lambda function

my_python_drift(x) = lambda x: -x
my_python_diff(x)  = lambda x: np.ones(len(x))

and so on. So more generally, my question is: Can I pass a Python lambda (or global) function as parameter to R, via rpy2?

Consider using rpy2's SignatureTranslatedAnonymousPackage (STAP) to import arbitrary R code as available package in Python environment. To demonstrate, below translates the Rdtq github written in R to Python using rpy2 :

R

# Loading required package: Rdtq
require(Rdtq)

# Assigning drift and diff functions
mydrift = function(x) { -x }
mydiff = function(x) { rep(1,length(x)) }

# Running rdtq()
test = rdtq(h=0.1, k=0.01, bigm=250, init=0, fT=1,
            drift=mydrift, diffusion=mydiff, method="sparse")

# Plotting output
plot(test$xvec, test$pdf, type='l')

Python

from rpy2 import robjects 
from rpy2.robjects.packages import STAP
from rpy2.robjects.packages import importr

# Loading required package: Rdtq
Rdtq = importr('Rdtq')

fct_string = """
my_drift <- function(x) { -x }
my_diff  <- function(x) { rep(1,length(x)) }
"""

# Creating package with above drift and diff methods
my_fcts = STAP(fct_string, "my_fcts")

# Running rdtq() --notice per Python's model: all methods are period qualified
test = Rdtq.rdtq(h=0.1, k=0.01, bigm=250, init=0, fT=1,
                 drift=my_fcts.my_drift(), diffusion=my_fcts.my_diff(), method="sparse")

# Load plot function
plot = robjects.r.plot

# Plotting by name index
plot(test[test.names.index('xvec')], test[test.names.index('pdf')], type='l')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM