Question

I have an generalized mixed effects model such as the following:

d <- data.frame(
    g = sample(c("A","B","C","D","E"), 250, replace=TRUE),
    x = runif(250, max=100),
    y = sample(c(0,1), 250, replace=TRUE)
)

require(lme4)

fm <- lmer(y ~ x + (1 + x | g), data=d, family=binomial)

I'd like to plot the random effect of the intercepts using dotplot but without plotting the random slope component of x. My problem is that I can't seem to figure out how to access just the intercept component and not the random slopes.

For example, what I want is the left hand side of this plot:

dotplot(ranef(fm, postVar=TRUE))

enter image description here

Using dotplot(ranef(fm, postVar=TRUE)$g[,2]) doesn't give me what I want even though I think it should! I've looked at str(fm), but didn't see anything that helped me get any closer.

Any help and hints would be much appreciated!

Was it helpful?

Solution

This should get you pretty close. I've been meaning to add support for lme4 objects to coefplot so maybe this be my catalyst.

theRan <- ranef(fm, postVar=TRUE)
pv <- attr(theRan$g, "postVar")
se <- pv[1, 1, ]
theIntercepts <- theRan$g[, 1, drop=F]
theFrame <- cbind(theIntercepts, se)
names(theFrame)[1] <- "Intercept"
theFrame$Low <- with(theFrame, Intercept - 2 * se)
theFrame$High <- with(theFrame, Intercept + 2 * se)
theFrame$Variable <- rownames(theFrame)
ggplot(theFrame, aes(y=Intercept, x=reorder(Variable, Intercept))) + geom_linerange(aes(ymin=Low, ymax=High), colour="black") + geom_point(, colour="blue") + coord_flip() + labs(y="Intercept", x=NULL)

OTHER TIPS

You were almost there in your original code:

dotplot(ranef(fm, postVar=TRUE))$g[1]

An additional tip to free the scales for each plot:

dotplot(ranef(fm, postVar=TRUE),
        scales = list(x =list(relation = 'free')))

You just need to be a little more clever about removing that other column of random effects:

re <- ranef(fm,postVar = TRUE)
re$g$x <- NULL
dotplot(re)

The reason your other method didn't work is that the dotplot method being dispatched still expects its input to look like a one element list, just as it would coming from ranef. So you just need to reach in and remove only that offending column, but leave the rest of the structure untouched.

You're not looking at the str() of the right thing.

re <- ranef(fm, postVar = TRUE)
str(re)

That shows you a list with the first item a data frame containing what you want. I'd just drop the $x column from it.

re[[1]]$x <- NULL
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top