首页 文章

plot.lm错误:$运算符对原子向量无效

提问于
浏览
2

我有以下回归模型与转换:

fit <- lm( I(NewValue ^ (1 / 3)) ~ I(CurrentValue ^ (1 / 3)) + Age + Type - 1,
           data = dataReg)
plot(fit)

但是 plot 给了我以下错误:

Error: $ operator is invalid for atomic vectors

关于我做错了什么的任何想法?

Notesummarypredictresiduals 都正常工作 .

1 回答

  • 4

    这实际上是一个非常有趣的观察 . 实际上,在 plot.lm 支持的所有6个图中,在这种情况下只有Q-Q图失败 . 考虑以下可重现的示例:

    x <- runif(20)
    y <- runif(20)
    fit <- lm(I(y ^ (1/3)) ~ I(x ^ (1/3)))
    ## only `which = 2L` (QQ plot) fails; `which = 1, 3, 4, 5, 6` all work
    stats:::plot.lm(fit, which = 2L)
    

    plot.lm 内部,Q-Q图简单生成如下:

    rs <- rstandard(fit)  ## standardised residuals
    qqnorm(rs)  ## fine
    ## inside `qqline(rs)`
    yy <- quantile(rs, c(0.25, 0.75))
    xx <- qnorm(c(0.25, 0.75))
    slope <- diff(yy)/diff(xx)
    int <- yy[1L] - slope * xx[1L]
    abline(int, slope)  ## this fails!!!
    

    错误:$运算符对原子向量无效

    So this is purely a problem of abline function! 注意:

    is.object(int)
    # [1] TRUE
    
    is.object(slope)
    # [1] TRUE
    

    intslope 都有class属性(读 ?is.object ;它是检查对象是否具有class属性的一种非常有效的方法) . 什么级别?

    class(int)
    # [1] AsIs
    
    class(slope)
    # [1] AsIs
    

    This is the result of using I(). Precisely, they inherits such class from rs and further from the response variable. That is, if we use I() on response, the RHS of the model formula, we get this behaviour.

    你可以在这里做一些实验:

    abline(as.numeric(int), as.numeric(slope))  ## OK
    abline(as.numeric(int), slope)  ## OK
    abline(int, as.numeric(slope))  ## fails!!
    abline(int, slope)  ## fails!!
    

    So abline(a, b) is very sensitive to whether the first argument a has class attribute or not.

    为什么?因为 abline 可以接受带有"lm"类的线性模型对象 . 里面 abline

    if (is.object(a) || is.list(a)) {
        p <- length(coefa <- as.vector(coef(a)))
    

    If a has a class, abline is assuming it as a model object (regardless whether it is really is!!!), then try to use coef to obtain coefficients. The check being done here is fairly not robust; we can make abline fail rather easily:

    plot(0:1, 0:1)
    a <- 0  ## plain numeric
    abline(a, 1)  ## OK
    class(a) <- "whatever"  ## add a class
    abline(a, 1)  ## oops, fails!!!
    

    错误:$运算符对原子向量无效

    So here is the conclusion: avoid using I() on your response variable in the model formula. 可以在协变量上使用 I() ,但不能在响应中使用 . lm 和大多数通用函数在处理此问题时都没有问题,但 plot.lm 会 .

相关问题