Background

I have to use a purged version of my glm object in a Shiny app because the original model object is too large. Thus, I cannot generate standard errors of prediction through that purged object. Instead, I will have to use the variance-covariance matrix (which I grabbed from the original model object) to calculate prediction variances/standard errors. In the app, I dynamically generate hypothetical observations on which I want to predict outcomes and their standard errors.

Problem

I'm left with the problem of creating a corresponding model matrix that I can multiply by the var-cov matrix. When I use model.matrix(), I often get errors because my hypothetical data do not always have more than one level for factor variables. I realize that I can hard code some logic to simply make the model matrix based on my understanding of the model formula. But it seems like something that probably already had a solution.

I made a simple example using a mini iris-like dataset which throws the error I'm talking about.

iris2 <- data.frame(Sepal.Length = c(3, 4), Species = c("setosa", "setosa"))
model.matrix( ~ Sepal.Length*Species, iris2)
1

There are 1 best solutions below

0
On BEST ANSWER

Maybe this was a stupid question. But I realized when I made that iris example (with the actual iris dataset) that model.matrix() doesn't actually throw an error if the factor variable has more than one level (even if it has only one unique value in the hypothetical sample). Because it needs to make binary indicators for factor variables, model.matrix() is left with no potential reference levels in my mini-example.

I used the purged model's "xlevels" object (model$xlevels), looped through the variables with levels, and re-factored those columns like this:

for(i in 1:length(model$xlevels)){
newdata[[names(model$xlevels)[i]]] <- factor(newdata[[names(model$xlevels)[i]]], levels = model$xlevels[[i]])
}

Note that I tried to use the purged model object, as well as model$terms, in the model.matrix()'s "object" input, but to no avail.

If there is a better way, I would appreciate someone responding! Otherwise, I hope this helps.