Reputation: 667
There is a R function (via the nlme package) lmList that contains a list of lm objects with a common model, after partitioning data according to a grouping factor. This has a lot of the useful methods that models typically have, such as predict. Is there an equivalent feature for glm?
I do see glmlist, but unlike lmlist it seems more to be a fancy container, with none of methods such as predict.
I.e. is there the equivalent of the following code for glm?
library(nlme)
fit <- lmList(disp ~ hp | vs, mtcars)
predict(fit,mtcars)
Upvotes: 1
Views: 150
Reputation: 4871
Quoting from the documentation of vcdExtra
, there does not seem to be one:
glmlist creates a glmlist object containing a list of fitted glm objects with their names. [...]
The intention is to provide object classes to facilitate model comparison, extraction, summary and plotting of model components, etc., perhaps using lapply or similar.
However, you can do just that and define your own predict method based on lapply
:
library(vcdExtra)
# simulate data
x <- rnorm(100)
y <- as.numeric(rnorm(100)>0)
fit <- glm(y~x, family=binomial(link=logit))
gl <- glmlist(fit,fit)
# define method
predict.glmlist <- function(object, ...){
expr <- substitute(predict.glm(obj,...))
lapply(object, function(obj) eval(expr))
}
# use method
predict(gl)
predict(gl, type="response")
Upvotes: 1
Reputation: 226182
The version of lmList
in the lme4
package can also handle GLM fits. It probably hasn't been extensively tested for this use case, so be careful/report any problems you find to https://github.com/lme4/lme4/issues/ ...
e.g.
library(lme4)
fit <- lmList(round(disp) ~ hp | vs, family=poisson, mtcars)
predict(fit,mtcars)
gives the predicted values on the linear predictor scale. Confusingly, predict(fit)
gives the fitted values on the response scale, i.e.
all.equal(c(predict(fit)),c(exp(predict(fit,mtcars))))
is TRUE
(in this case, and whenever the model uses a log link). predict(fit,mtcars,type="response")
silently ignores the type
specification ...
Upvotes: 2