2012-02-14 50 views
3

我想重寫默認predict.lm功能由於錯誤:如何覆蓋R中的默認S3函數?

library(datasets) 
# Just a regular linear regression 
fit <- lm(mpg~disp+hp+wt+drat, data=mtcars) 
termplot(fit, terms=2, se=T) 

給出了這樣的錯誤:

Error in predict.lm(model, type = "terms", se.fit = se, terms = terms) : 
    subscript out of bounds 

我知道那裏的錯誤是,我已經發送的等待電子郵件核心郵件列表的核準,但同時我想測試我自己的predict.lm函數來解決這個問題。我明白,我需要重新定義預測S3的功能,但在運行此代碼時:

setMethod("predict", "lm", predict.lm2) 
getMethod("predict", "lm") 

實現getMethod返回我的新功能,如預期,但termplot仍然運行老的功能。 methods("predict")還顯示舊的predict.lm仍然存在,我認爲它可能是調用順序或我需要調整的東西。任何人都知道如何做到這一點?

+0

您可以嘗試設置模型的類。 'class(fit)< - c(「lm2」,「lm」)' – James 2012-02-14 10:44:48

+0

然後它抱怨說缺少lm2類的定義 – 2012-02-14 10:55:15

+0

您使用setMethod時不使用S3,而使用S4。這會帶來麻煩。 – 2012-02-14 12:42:40

回答

4

@ James的評論建議您定義您自己的lm2類, ,其延伸lm,並實現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) 
+0

謝謝,這幾乎解決了這個問題,雖然我的bug修復predict.lm2函數會導致一個小錯誤:找不到函數「qr.lm」 - 我想這是由於lm類的一些內部函數。我如何訪問lm的內部功能?我粘貼了我的predict.lm2函數[在pastebin中](http://pastebin.com/FARH1gC0) – 2012-02-14 11:42:30

+2

由於該函數未導出,因此必須明確指定名稱空間:'stats ::: qr.lm' ,每次出現。 – 2012-02-14 12:07:52

+0

謝謝,這就像一個魅力 – 2012-02-14 12:19:29