通过rpy2将Python Lambda函数传递给R.

时间:2017-08-16 02:25:26

标签: python r lambda rpy2

我想在R库Rdtq周围编写一个Python包装器 (https://github.com/cran/Rdtq)。 该库(或更确切地说,类实例)将两个函数作为主要输入:漂移f(x)和扩散g(x)。例如,

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

由于我正在编写一个围绕Rdtq类的包装器,我想直接从Python传递漂移和扩散函数,理想情况下通过lambda函数

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

等等。更一般地说,我的问题是: 我可以通过rpy2将Python lambda(或全局)函数作为参数传递给R吗?

1 个答案:

答案 0 :(得分:0)

考虑使用rpy2的SignatureTranslatedAnonymousPackage (STAP)将任意R代码作为Python环境中的可用包导入。为了演示,下面使用rpy2将用R编写的Rdtq github转换为Python:

<强> - [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')