r - plot.lm Error: $ operator is invalid for atomic vectors -
i have following regression model transformations:
fit <- lm( i(newvalue ^ (1 / 3)) ~ i(currentvalue ^ (1 / 3)) + age + type - 1, data = datareg) plot(fit) but plot gives me following error:
error: $ operator invalid atomic vectors any ideas doing wrong?
note: summary, predict, , residuals work correctly.
this quite interesting observation. in fact, among 6 plots supported plot.lm, q-q plot fails in case. consider following reproducible example:
x <- runif(20) y <- runif(20) fit <- lm(i(y ^ (1/3)) ~ i(x ^ (1/3))) ## `which = 2l` (qq plot) fails; `which = 1, 3, 4, 5, 6` work stats:::plot.lm(fit, = 2l) inside plot.lm, q-q plot produced follow:
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) ## fails!!! error: $ operator invalid atomic vectors
so purely problem of abline function! note:
is.object(int) # [1] true is.object(slope) # [1] true i.e., both int , slope has class attribute (read ?is.object; efficient way check whether object has class attribute). class?
class(int) # [1] asis class(slope) # [1] asis this result of using i(). precisely, inherits such class rs , further response variable. is, if use i() on response, rhs of model formula, behaviour.
you can few experiment here:
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) sensitive whether first argument a has class attribute or not.
why? because abline can accept linear model object "lm" class. inside abline:
if (is.object(a) || is.list(a)) { p <- length(coefa <- as.vector(coef(a))) if a has class, abline assuming model object (regardless whether is!!!), try use coef obtain coefficients. check being done here not robust; can make abline fail rather easily:
plot(0:1, 0:1) <- 0 ## plain numeric abline(a, 1) ## ok class(a) <- "whatever" ## add class abline(a, 1) ## oops, fails!!! error: $ operator invalid atomic vectors
so here conclusion: avoid using i() on response variable in model formula. ok have i() on covariates, not on response. lm , generic functions won't have trouble dealing this, plot.lm will.
Comments
Post a Comment