Reputation: 13116
I am trying to call R glm.nb
from rpy2
:
from rpy2 import robjects
from rpy2.robjects.packages import importr
MASS = importr('MASS')
stats = importr('stats')
def glm_nb(x,y):
formula = robjects.Formula('y~x')
env = formula.environment
env["x"] = x
env["y"] = y
fitted = MASS.glm_nb(formula)
# fitted = stats.glm(formula)
return fitted
Test:
N = 100
x = np.random.rand(N)
y = x + np.random.poisson( 10, N)
fitted = glm_nb(x, np.round(y))
Returns an error:
104 for k, v in kwargs.items():
105 new_kwargs[k] = conversion.py2ri(v)
--> 106 res = super(Function, self).__call__(*new_args, **new_kwargs)
107 res = conversion.ri2ro(res)
108 return res
RRuntimeError: Error in x[good, , drop = FALSE] * w : non-conformable arrays
However when I run simple glm
it runs OK. What can be the problem and how can one debug it?
Upvotes: 3
Views: 622
Reputation: 11555
What is happening is that the underlying R code is expecting "vectors" rather that arrays, but the Python objects are arrays.
A simple fix is to give the R function in the package MASS you are calling what it wants / expects. The following line in your test can be changed:
fitted = glm_nb(x, np.round(y))
...to this:
import array
fitted = glm_nb(array.array('f', x), array.array('f', np.round(y)))
...or to this:
from rpy2.robjects.vectors import FloatVector
fitted = glm_nb(FloatVector(x), FloatVector(np.round(y)))
Upvotes: 1
Reputation: 107687
The essential problem involves the data structure of matrix and array in R. Below reproduces your error in R with fix, the challenge of replicating fix in rpy2
, and a working solution:
R Error and Fixes
library(MASS)
# ARRAY
x <- array(rnorm(100))
y <- as.integer(x) + array(rpois(100, 10))
model2 <- glm.nb(y~x)
Error in x[good, , drop = FALSE] * w : non-conformable arrays
However, three fixes are available: 1) use of matrix (the two-dimensional special type of array); 2) equivalently defined array (specifying dim
argument); and 3) matrix conversion. Do note: a warning of iteration limit may appear depending on random values but still runs.
# MATRIX
x <- matrix(rnorm(100))
y <- as.integer(x) + matrix(rpois(100, 10))
model1 <- glm.nb(y~x)
# EQUIVALENT ARRAY
x <- array(rnorm(100),c(100,1))
y <- as.integer(x) + matrix(rpois(100, 10),c(100,1))
model2 <- glm.nb(y~x)
# EXPLICIT MATRIX CONVERSION (USED IN WORKING SOLUTION)
x <- as.matrix(array(rnorm(100)))
y <- as.integer(x) + as.matrix(array(rpois(100, 10)))
model3 <- glm.nb(y~x)
Challenge
Python's rpy2
does not pass a numpy matrix into an R matrix effectively from my workings of the script as a different error emerges for both stat's simple glm()
and MASS' glm.nb()
:
import numpy as np
from rpy2 import robjects
from rpy2.robjects.packages import importr
from rpy2.robjects.numpy2ri import numpy2ri
MASS = importr('MASS')
#rpy2 + negative binomial glm
stats = importr('stats')
def glm_nb(x,y):
formula = robjects.Formula('y~x')
env = formula.environment
env["x"] = x
env["y"] = y
fitted = MASS.glm_nb(formula)
# fitted = stats.glm(formula)
return fitted
N = 100
x = np.random.rand(N)
x = np.asmatrix(x) # PYTHON CONVERSION TO MATRIX
r_x = numpy2ri(x)
# REPLACED NP.ROUND FOR AS.TYPE() TO COMPARE WITH R
y = x.astype(int) + np.random.poisson(10, N)
y = np.asmatrix(y) # PYTHON CONVERSION TO MATRIX
r_y = numpy2ri(y)
fitted = glm_nb(r_x, r_y)
rpy2.rinterface.RRuntimeError: Error in glm.fitter(x = X, y = Y, w = w, start = start, etastart = etastart, : object 'fit' not found
Even numpy2ri.activate()
failed to convert the numpy matrices:
from rpy2.robjects import numpy2ri
robjects.numpy2ri.activate()
r_x = numpy2ri.ri2py(x)
r_y = numpy2ri.ri2py(y)
NotImplementedError: Conversion 'ri2py' not defined for objects of type
'<class 'numpy.matrixlib.defmatrix.matrix'>'
Working Solution
Simply interfacing with the robjects.r()
and have R convert the array object to matrix worked. Recall the third fix above:
N = 100
x = np.random.rand(N)
r_x = numpy2ri(x)
y = x.astype(int) + np.random.poisson(10, N)
r_y = numpy2ri(y)
from rpy2.robjects import r
r.assign("y", r_y)
r.assign("x", r_x)
r("x <- as.matrix(x)")
r("y <- as.matrix(y)")
r("res <- glm.nb(y~x)")
r_result = r("res[1:5]")
# CONVERSION INTO PY DICTIONARY
from rpy2.robjects import pandas2ri
pandas2ri.activate()
pyresult = pandas2ri.ri2py(r_result)
print(pyresult) # OUTPUTS COEFF, RESID, FITTED VALS, EFFECTS, R
# OR OLDER DEPRECATED CONVERSION
import pandas.rpy.common as com
pyresult = com.convert_robj(r_result)
print(pyresult) # OUTPUTS COEFF, RESID, FITTED VALS, EFFECTS, R
Command Line Solution
If allowable in your application, simply call the R modeling script from Python as a command line subprocess, bypassing any need of rpy2
and even pass arguments as needed:
from subprocess import Popen, PIPE
command = 'Rscript.exe'
path2Script = 'path/to/Script.R'
args = ['arg1', 'arg2', 'arg3']
cmd = [command, path2Script] + args
p = Popen(cmd,stdin= PIPE, stdout= PIPE, stderr= PIPE)
output,error = p.communicate()
if p.returncode == 0:
print('R OUTPUT:\n {0}'.format(output))
else:
print('R ERROR:\n {0}'.format(error))
Upvotes: 2