[R] glm.nb and Error in x[good, , drop = FALSE] * w : non-conformable arrays

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Fri Apr 21 10:08:46 CEST 2023


On Fri, 21 Apr 2023 09:02:37 +0200
Patrick Giraudoux <patrick.giraudoux using univ-fcomte.fr> wrote:

> I meet an error with glm.nb that I cannot explain the origin (and
> find a fix). The model I want to fit is the following:
> 
> library(MASS)
> 
> glm.nb(deg~offset(log(durobs))+zone,data=db)
> 
> and the data.frame is dumped below.

Thank you for providing both the code and a small piece of data that
reproduces the error!

(It almost worked. Your mailer automatically generated a plain text
version of the e-mail and put Unicode non-breaking spaces in there. R
considers it a syntax error to encounter any of the various Unicode
space-like characters outside string literals.)

> deg = structure(c(0, 1, 0, 3, 0, 1, 0, 2, 1, 0, 3, 0, 0, 0, 4, 1, 0,
> 0, 0, 0, 4, 0, 0, 0, 4, 3, 2, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
> 0, 3, 2, 3, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 2,
> 0, 0, 0, 2, 1, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2,
> 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 1, 0, 0, 1, 3, 2,
> 1, 2, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 2,
> 1, 1, 0), dim = 135L, class = "table")

The problem is that `deg` is a table, which ends up making the
effective weights a table too. tables are arrays, and element-wise
product rules are stricter for them than for plain matrices. The code
makes use of the ability to take an element-wise product between a
matrix and a vector of the same length as the number of rows in the
matrix:

matrix(1:12, 4) * 1:4 # works
matrix(1:12, 4) * as.array(1:4) # results in the same error

# the right way to take products with an array is to make sure that the
# shapes match exactly
matrix(1:12, 4) * as.array(cbind(1:4, 1:4, 1:4))

One possible solution is to to remove all attributes from db$deg:

db$deg <- as.vector(db$deg)

This way the values of the expressions involved in glm.fit end up being
of the expected type, and the function completes successfully.

-- 
Best regards,
Ivan



More information about the R-help mailing list