简体   繁体   English

将 R package pmultinom 与 PyRserve 一起使用

[英]Using R package pmultinom with PyRserve

I am trying to utilize the R package pmultinom in Python by using pyRserve, with numbers that are imported to the code.我正在尝试通过使用 pyRserve 在 Python 中使用 R package pmultinom,并将数字导入到代码中。 I am having the following error:我有以下错误:

REvalError: Error: object 'pmultinom' not found. REvalError:错误:未找到 object 'pmultinom'。

import pyRserve
num1 = 1
num2 = 2
num3 = 3
num4 = 4
num5 = 5
num6 = 6
vec1 = (.2,.3,.5)

r_script = '''
           install.packages(pmultinom)
           library(pmultinom)
        
           pmultinom(
           '''
full_rscript =( r_script + 'lower=c(' + str(num1) + ',' + str(num2) + ',' + str(num3) + 
                               '), upper=c(' + str(num4) + ',' + str(num5) + ',' +  
                                   str(num6) + 
                                   '), size=' + str(num7) + ', probs=' + str(vec1) + ')'
           )
output = conn.eval(full_rscript) 

When I try a similar code with当我尝试使用类似的代码时

conn.r.pmultinom(…)

I get an error that the function can't be found.我收到一个错误,提示找不到 function。

Here is one option with pyper as we have used it in production settings and it worked without any issues这是pyper的一个选项,因为我们已经在生产设置中使用它并且它没有任何问题

from pyper import *
r = R(use_pandas=True)
num1 = 1
num2 = 2
num3 = 3
num4 = 4
num5 = 5
num6 = 6
num7 = 20000
vec1 = (.17649, .17542, .15276, .15184, .17227, .17122)

We don't need to create individual objects, it can be a list or tuple as in vec1 .我们不需要创建单独的对象,它可以是一个列表或元组,如vec1 Just to demonstrate只是为了展示

r.assign("rnum1", num1)
r.assign("rnum2", num2)
r.assign("rnum3", num3)
r.assign("rnum4", num4)
r.assign("rnum5", num5)
r.assign("rnum6", num6)
r.assign("rnum7", num7)
r.assign("rvec1", vec1)

Create an expression创建表达式

expr = "library(pmultinom); out <- pmultinom(lower = c(rnum1, rnum2, rnum3, rnum4, rnum5, rnum6), upper = rep.int(3630, 6), size = rnum7, probs = rvec1, method = 'exact')"

and evaluate the expression and get the output并评估表达式并获得 output

r(expr)
r.get("out")
#0.95663799758361

-testing from R side directly - 直接从 R 侧测试

num1 = 1
num2 = 2
num3 = 3
num4 = 4
num5 = 5
num6 = 6
num7 = 20000
vec1 = c(.17649, .17542, .15276, .15184, .17227, .17122)


pmultinom(lower = c(num1, num2, num3, num4, num5, num6), 
  upper = rep.int(3630, 6), size = num7, probs = vec1, 
       method = 'exact')
#[1] 0.956638

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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