Skip to content

Instantly share code, notes, and snippets.

@mainambui
Forked from Martin-Jung/fake.predict.clmm
Last active February 22, 2020 16:35
Show Gist options
  • Save mainambui/c803aaf857e54a5c9089ea05f91473bc to your computer and use it in GitHub Desktop.
Save mainambui/c803aaf857e54a5c9089ea05f91473bc to your computer and use it in GitHub Desktop.
Predicting model averaged clmm models to new data
# Arguments:
# - model = a clmm model
# - modelAvg = a clmm model average (object of class averaging)
# - newdata = a dataframe of new data to apply the model to
# Returns a dataframe of predicted probabilities for each row and response level
fake.predict.clmm <- function(modelAvg, newdata) {
# Actual prediction function
pred <- function(eta, theta, cat = 1:(length(theta) + 1), inv.link = plogis) {
Theta <- c(-1000, theta, 1000)
sapply(cat, function(j) inv.link(Theta[j + 1] - eta) - inv.link(Theta[j] - eta))
}
# Multiply each row by the coefficients
#coefs <- c(model$beta, unlist(model$ST))##turn off if a model average is used
beta <- modelAvg$coefficients[2,3:12]
coefs <- c(beta, unlist(modelAvg$ST))
xbetas <- sweep(newdata, MARGIN=2, coefs, `*`)
# Make predictions
Theta<-modelAvg$coefficients[2,1:2]
#pred.mat <- data.frame(pred(eta=rowSums(xbetas), theta=model$Theta))
pred.mat <- data.frame(pred(eta=rowSums(xbetas), theta=Theta))
#colnames(pred.mat) <- levels(model$model[,1])
a<-attr(modelAvg, "modelList")
colnames(pred.mat) <- levels(a[[1]]$model[,1])
pred.mat
}
@mainambui
Copy link
Author

Feb 6 2016: modified the original by adding functionality to use model averaged coefficients

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment