I'm attempting to plot only certain observations from my random effects model (since the actual data set has a lot of observations).
Here is an example of the analysis:
# Load packages
library(lme4)
library(lattice)
# Load sleep data
data(sleepstudy)
# Model
fit <- lmer(Reaction ~ Days + (1 + Days|Subject), data = sleepstudy)
# Plot random effects
dotplot(ranef(fit, condVar = T))
The plot looks like this:
What if I wanted to only plot the results for subjects 337, 310, 333, and 349?
I've tried saving the ranef()
results, selecting the subjects of interest, and then building a plot from there but that wont work as I lose the error bars.
We need to manipulate the ranef.mer
object.
library(lme4)
library(lattice)
data(sleepstudy)
fit <- lmer(Reaction ~ Days + (1 + Days|Subject), data=sleepstudy)
First, we store it.
r.int <- ranef(fit, condVar=TRUE)
Second, we create a vector of the desired subset row numbers.
s <- c(337, 310, 333, 349)
Third, inside a lapply
function we subset both in the list, the data.frame
and importantly the attributes, where the variances are hidden in an array.
r.int <- lapply(r.int, function(x) {
s2 <- which(rownames(x) %in% s)
x <- x[s2, ]
attributes(x)$postVar <- attributes(x)$postVar[, , s2]
return(x)
})
Fourth we hack the required class label.
class(r.int) <- "ranef.mer"
Et voilà, we finally can plot our desired selection.
dotplot(r.int)