[英]Passing a custom function in BLME r package via rpy2 in python
[英]Passing Python Lambda function to R via rpy2
我想圍繞R庫Rdtq( https://github.com/cran/Rdtq )編寫一個Python包裝器。 該庫(或更確切地說,類實例)將兩個函數作為主要輸入:漂移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?
考慮使用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')
蟒蛇
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.