I want to override the default predict.lm function due to a bug:
library(datasets)
# Just a regular linear regression
fit <- lm(mpg~disp+hp+wt+drat, data=mtcars)
termplot(fit, terms=2, se=T)
Gives this error:
Error in predict.lm(model, type = "terms", se.fit = se, terms = terms) :
subscript out of bounds
I know where the bug is and I've sent an email that awaits approval by the core mailing list but in the meantime I would like to test my own predict.lm function to fix this. I've understood that I need to redefine the S3 function for predict but when running this code:
setMethod("predict", "lm", predict.lm2)
getMethod("predict", "lm")
The getMethod returns my new function as expected but the termplot still runs the old function. The methods("predict")
shows also that the old predict.lm is still there and I think it might be the call-order or something that I need to adjust. Anyone familiar with how to do this?
@James's comment suggests to define your own lm2
class,
that extends lm
, and to implement predict.lm2
.
class(fit) <- c("lm2", class(fit))
predict.lm2 <- function(...) {
# The function with your bugfix
cat("Inside predict.lm2\n")
predict.lm(...)
}
termplot(fit, terms=2, se=T)