2017-08-16 34 views
0

我想围绕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吗?

+0

这是一个[XY问题](https://开头meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。您只告诉我们您的Y解决方案,但不解释X问题。请给出真实的,完整的方案,并提供具体或可重复的例子。虽然你可能会这样想,但你可能需要'lambda'。 – Parfait

+0

够公平的,我已经调整了这个问题。 – user56643

回答

0

考虑使用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') 
+0

虽然这确实是一个很好的解决方法,但它不适用于我的问题。函数'my_drift'和'my_diff'是在运行时以非平凡的方式生成的,我不能明确地提供它们。 – user56643

+0

不确定这是什么意思,或者你真的在问什么。祝你好运! – Parfait

+0

我的意思是我不能以字符串的形式明确指定函数。编译代码时,我不知道函数的形状,它在运行时自动确定。具体来说,我有一些随机数据作为输入,然后对数据进行拟合和整合。这给出了我感兴趣的漂移函数。这解释了为什么我需要将函数作为对象传递,并且我不能将该函数明确地作为字符串写入。 – user56643