Skip to content
Prev 6542 / 20628 Next

Extractor Functions

Martin, here is a first request!

The following type of plot (cf Figure 10.3 in "Data Analysis and Graphics Using R", 2nd & 3rd editions)
often makes sense for a multilevel model:

library(DAAG)
science <- na.omit(science)
science$class <- factor(science$class)
science$school <- factor(science$school)
science1.lmer <- lmer(like ~ sex + PrivPub + (1 | school:class),
                          data = science)
ranf <- ranef(obj = science1.lmer, drop=TRUE)[["school:class"]]
ranflev <- science1.lmer at flist[["school:class"]]
privpub <- science[match(names(ranf), ranflev), "PrivPub"]
count <- unclass(table(ranflev))
plot(sqrt(count), ranf, xaxt="n", pch=as.numeric(privpub),
         xlab="# in class (square root scale)",
         ylab="Estimate of class effect")

Now define the following function:

ranefWithFactors <-
    function(obj=science1.lmer, term="school:class", fac="PrivPub",
             count=TRUE, data=science){
     ranf <- ranef(obj = obj, drop=TRUE)[[term]]
     ranflev <- obj at flist[[term]]
     ## Check that each value (level) corresponds to a unique level of PrivPub
     if(count) num <- unclass(table(ranflev)) else num <- NULL
     matchfac <- data[match(names(ranf), ranflev), fac]
     check <- apply(table(ranflev, data[,fac]),1,function(x)sum(x==0))
     if(any(check)!=1)stop(paste("Each value (level) of", term,
                        "must correspond to a unique level of", fac))
     df <- data.frame(effect=ranf, fac=matchfac, count=num)
     df
 }

library(DAAG)
science <- na.omit(science)
science$class <- factor(science$class)
science$school <- factor(science$school)
science1.lmer <- lmer(like ~ sex + PrivPub + (1 | school:class), data = science)

df <- ranefWithFactors(obj=science1.lmer, term="school:class", fac="PrivPub",
             count=TRUE, data=science)

xyplot(effect ~ sqrt(count), xaxt="n", groups=fac, data=df,
         auto.key=list(columns=2),
         xlab="# in class (square root scale)", ylab="Estimate of class effect")

The function should doubtless allow for 'fac' to be a vector of factor names.
It should be possible to dispense with the argument data -- I've not checked
how to circumvent that.

Thanks for opening up the issue of further extractor functions.

John Maindonald             email: john.maindonald at anu.edu.au
phone : +61 2 (6125)3473    fax  : +61 2(6125)5549
Centre for Mathematics & Its Applications, Room 1194,
John Dedman Mathematical Sciences Building (Building 27)
Australian National University, Canberra ACT 0200.
http://www.maths.anu.edu.au/~johnm
On 12/08/2011, at 12:11 AM, Martin Maechler wrote: