# A. This shows how to use a custom fitting function, taking the example of mixed models and lmer
# we load the lme4 package
library(lme4)
# some random data
vy = 1:100
va = runif(100)
vb = runif(100)
vc = factor(round(runif(100)))
# assume we want to use a random effect to control for the factor vc
# There are three small steps to take:
# 1. we first define a wrapper to lmer
lmer.glmulti <- function (formula, data, random = "", ...) {
lmer(paste(deparse(formula), random), data = data, ...)
}
# the fixed-effects are passed as formula, and the random effects are passed as "random"
# 2. We now define the corresponding getfit method (allowing access to fitted parameters)
setMethod('getfit', 'mer', function(object, ...) {
summary(object)@coefs[,1:2]
})
# 3.Last, we must provide the corresponding aicc method, since the default will not work with mer objects
setMethod('aicc', 'mer', function(object, ...) {
liliac<- logLik(object)
k<-attr(liliac,"df")
n= object@dims['n']
return(-2*as.numeric(liliac[1]) + 2*k*n/max(n-k-1,0))
})
# we are now ready to go:
glmulti(vy~va*vb,level=2,fitfunc=lmer.glmulti,random="+(1|vc)")-> bab
plot(bab)
summary(bab)
weightable(bab)
coef(bab)
# fixed-effects are shuffled and the random part is constant
# B. This shows how to do the same for zero-inflated poisson models
# we load the required package
library(pscl)
# a random vector of count data
round(runif(100, 0,20)*round(runif(100)))-> vy2
# 1. The wrapper function
zeroinfl.glmulti=function(formula, data, inflate = "|1",...) {
zeroinfl(as.formula(paste(deparse(formula), inflate)),data=data,...)
}
# 2 and 3. Unlike before, the default getfit and aicc method will work for zeroinfl objects, so no need to redefine them!
# we can proceed directly
glmulti(vy2~va*vb,fitfunc=zeroinfl.glmulti,inflate="|1")->bab
# C. This shows how to include some terms in ALL the models
# As above, we just prepare a wrapper of the fitting function
glm.redefined = function(formula, data, always="", ...) {
glm(as.formula(paste(deparse(formula), always)), data=data, ...)
}
# we then use this fitting function in glmulti
glmulti(vy~va,level=1,fitfunc=glm.redefined,always="+vb")-> bab
# va will be shuffled but vb is always included in the models
# this procedure allows support of arbitrarily any fitting function, or the use of sophisticated constraints on the model structureRun the code above in your browser using DataLab