Create lm object from data/coefficients

拜拜、爱过 提交于 2020-01-01 04:54:07

问题


Does anyone know of a function that can create an lm object given a dataset and coefficients?

I'm interested in this because I started playing with Bayesian model averaging (BMA) and I'd like to be able to create an lm object out of the results of bicreg. I'd like to have access to all of the nice generic lm functions like diagnostic plotting, predict, cv.lm etc.

If you are pretty sure such a function doesn't exist that's also very helpful to know!

library(BMA)
mtcars_y <- mtcars[, 1] #mpg
mtcars_x <- as.matrix(mtcars[,-1])
res <- bicreg(mtcars_x, mtcars_y)

summary(res)
res$postmean # bma coefficients

# The approximate form of the function
# I'm looking for
lmObject <- magicFunction(data=mtcars, coefficients=res$postmean)

回答1:


There is no function that I am aware of that does this. One could of course be made. All that your magicFunction would need to do is create a list with elements:

> names(fakeModel)
[1] "coefficients"  "residuals"     "effects"       "rank"         
 [5] "fitted.values" "assign"        "qr"            "df.residual"  
 [9] "xlevels"       "call"          "terms"         "model"  

then make it an lm object

> class(fakeModel) <- c("lm")

Let me just say that I think that this is a bad idea though. Whose to say that the generic function that you apply will be applicable to a bicreg object. For example, how would you interpret AIC(fakeModel)?

You are better off creating your own functions to do diagnostics and prediction.




回答2:


It seems you can compute your lm object as usual, and then modify the coefficients afterwards by modifying the $coefficients attribute of your lm() result.

See this question and results for more details :

http://tolstoy.newcastle.edu.au/R/e2/help/07/08/24294.html

Not sure it corresponds to what you want to do, though...



来源:https://stackoverflow.com/questions/2062194/create-lm-object-from-data-coefficients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!