Bug 17407 - Multivariate lm does not allow matrix offset.
Summary: Multivariate lm does not allow matrix offset.
Alias: None
Product: R
Classification: Unclassified
Component: Models (show other bugs)
Version: R 3.5.0
Hardware: All All
: P5 enhancement
Assignee: R-core
Depends on:
Reported: 2018-04-18 04:40 UTC by Pavel N. Krivitsky
Modified: 2018-07-27 15:45 UTC (History)
1 user (show)

See Also:


Note You need to log in before you can comment on or make changes to this bug.
Description Pavel N. Krivitsky 2018-04-18 04:40:31 UTC
# Code to reproduce: #

lm(cbind(mpg,qsec)~1, data=mtcars, offset=cbind(wt,wt*2))

# Expected result: #

An object of class "mlm", fit with mpg offset by wt and qsec offset by wt*2.

# Actual result: #

Error in lm(cbind(mpg, qsec) ~ 1, data = mtcars, offset = cbind(wt, wt*2)) : 
  number of offsets is 64, should equal 32 (number of observations)

# Notes: #

It looks like model.frame() and model.offset() functions can handle matrix offsets seamlessly, as does the rest of the code, and the problem seems to stem from an overly strict check in lm() implementation (lm.R line 47 as of r73480):

    offset <- as.vector(model.offset(mf))
    if(!is.null(offset)) {
        if(length(offset) != NROW(y))
            stop(gettextf("number of offsets is %d, should equal %d (number of observations)",
                          length(offset), NROW(y)), domain = NA)

Modifying this to
1) not convert output of model.offset(mf) to a vector unless y is a vector, and
2) if y and offset are matrices, check that their dimensions are identical.
should enable lm() to take matrix offsets, as far as I can tell.

I would he happy to submit a patch.
Comment 1 Martin Maechler 2018-07-27 10:01:03 UTC
(In reply to Pavel N. Krivitsky from comment #0)

It looks to me that you are right in everything you say.

Note that the `as.vector(.)` there is mainly for dropping attributes (efficiency) and for treating 1d-array identically to vectors.

I'm testing a patch myself, currently.
No need to send yours.

Thank you for your constructive and careful report!

Comment 2 Martin Maechler 2018-07-27 15:45:39 UTC
Changes now committed to R-devel svn  75008  [among new features].