通过rpy2将Python Lambda函数传递给R
问题描述:
我想围绕R库Rdtq (https://github.com/cran/Rdtq)编写一个Python包装器。 该库(或更确切地说,类实例)将主要输入作为两个函数:漂移f(x)和扩散g(x)。例如,通过rpy2将Python Lambda函数传递给R
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吗?
答
考虑使用rpy2的SignatureTranslatedAnonymousPackage (STAP)在Python环境中导入任意R代码作为可用包。为了演示,写入中的R到Python的Rdtq github使用rpy2
以下转换:
ř
# 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')
这是一个[XY问题](https://开头meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。您只告诉我们您的Y解决方案,但不解释X问题。请给出真实的,完整的方案,并提供具体或可重复的例子。虽然你可能会这样想,但你可能需要'lambda'。 – Parfait
够公平的,我已经调整了这个问题。 – user56643