pythonrrservepyrserve

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. I am having the following error:

REvalError: Error: object 'pmultinom' not found.

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.


Solution

  • Here is one option with pyper as we have used it in production settings and it worked without any issues

    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. 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

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

    -testing from R side directly

    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