## generate one response, two predictors and one factor (random effect)
set.seed(101)
resp <- runif(100,1,100)
pred1<- rnorm(100,
mean=rep(resp[1:50],2)+rep(c(-10,20),each=50),
sd=rep(c(10,5),each=50))
pred2<- rnorm(100, resp-10, 10)
NOTE that you should probably not be trying to fit a random
effect for an grouping variable with only two levels -- this will
almost invariably result in an estimated random-effect variance of zero,
which will in turn put your predicted lines right on top of each
other -- I'm switching from gl(2,50)
to gl(10,10)
...
RF1<-gl(10,10)
d <- data.frame(resp,pred1,pred2,RF1)
#lmer
library(lme4)
mod <- lmer(resp ~ pred1 + pred2 + (1|RF1),data=d)
The development version of lme4
has a predict()
function
that makes this a little easier ...
- Predict for a range of
pred1
with pred2
equal to its mean,
and vice versa. This is all a little bit cleverer than it needs
to be, since it generates all the values for both focal predictors
and plots them with ggplot in one go ...
()
nd <- with(d,
rbind(data.frame(expand.grid(RF1=levels(RF1),
pred1=seq(min(pred1),max(pred1),length=51)),
pred2=mean(pred2),focus="pred1"),
data.frame(expand.grid(RF1=levels(RF1),
pred2=seq(min(pred2),max(pred2),length=51)),
pred1=mean(pred1),focus="pred2")))
nd$val <- with(nd,pred1[focus=="pred1"],pred2[focus=="pred2"])
pframe <- data.frame(nd,resp=predict(mod,newdata=nd))
library(ggplot2)
ggplot(pframe,aes(x=val,y=resp,colour=RF1))+geom_line()+
facet_wrap(~focus,scale="free")
- Alternatively, focusing just on
pred1
and generating predictions for a (small/discrete) range of pred2
values ...
()
nd <- with(d,
data.frame(expand.grid(RF1=levels(RF1),
pred1=seq(min(pred1),max(pred1),length=51),
pred2=seq(-20,100,by=40))))
pframe <- data.frame(nd,resp=predict(mod,newdata=nd))
ggplot(pframe,aes(x=pred1,y=resp,colour=RF1))+geom_line()+
facet_wrap(~pred2,nrow=1)
You might want to set scale="free"
in the last facet_wrap()
... or
use facet_grid(~pred2,labeller=label_both)
For presentation you might want to replace the colour
aesthetic,
with group
, if all you want to do is distinguish among groups
(i.e. plot separate lines) rather than identify them ...
pred2
equal to its mean) and plot the slope with respect topred1
for that value. Or you could pick several values ofpred2
and plot a (set of) lines for each one, possibly in separate subplots, or (ugliest) do 3D plots and plot planesresp~f(pred1,pred2)
instead. – Balaklava