在ggplot2中绘制具有预测值的低级交互

时间:2018-11-03 00:38:58

标签: r ggplot2

sub <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20)
f1 <- c("f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m")
f2 <- c("c1","c1","c1","c1","c1","c1","c1","c1","c1","c1","c2","c2","c2","c2","c2","c2","c2","c2","c2","c2","c1","c1","c1","c1","c1","c1","c1","c1","c1","c1","c2","c2","c2","c2","c2","c2","c2","c2","c2","c2")
f3 <- c(0.03,0.03,0.49,0.49,0.33,0.33,0.20,0.20,0.13,0.13,0.05,0.05,0.47,0.47,0.30,0.30,0.22,0.22,0.15,0.15, 0.03,0.03,0.49,0.49,0.33,0.33,0.20,0.20,0.13,0.13,0.05,0.05,0.47,0.47,0.30,0.30,0.22,0.22,0.15,0.15)
y <- c(0.9,1,98,96,52,49,44,41,12,19,5,5,89,92,65,56,39,38,35,33, 87,83,5,7,55,58,67,61,70,80,88,90,0.8,0.9,55,52,55,58,70,69)

dat <- data.frame(sub=sub, f1=f1, f2=f2, f3=f3, y=y)

m <- lmer(y ~ f1*f2*f3 + (1|sub), data=dat)

只有f1*f3相互作用才有意义,因此现在我想使用模型m的预测值绘制此相互作用。我尝试过

X <- with(dat, expand.grid(f1=unique(f1), f3=range(f3)))
X$Predicted <- predict(m, newdata=X, re.form=NA)

但出现错误...

如果我添加f2并绘制结果

X <- with(dat, expand.grid(f1=unique(f1), f3=range(f3), f2=unique(f2)))
X$Predicted <- predict(m, newdata=X, re.form=NA)
ggplot(X, aes(f3, Predicted)) +  geom_path(aes(color=f2)) + facet_wrap(~f1)

我在每个面板中都有两个与f2的水平相对应的斜率,但是我只希望模型f1*f3的{​​{1}}交互作用(没有m)。有人知道我该怎么解决吗?

1 个答案:

答案 0 :(得分:0)

effects软件包很有用:

library(effects)
fit <- effect('f1:f3', m)   # add xlevels = 100 for higher resolution CI's
fit_df <- as.data.frame(fit)

ggplot() +
  geom_point(aes(f3, y, color = f1), dat) +
  geom_ribbon(aes(f3, ymin = lower, ymax = upper, fill = f1), fit_df, alpha = 0.3) +
  geom_line(aes(f3, fit, color = f1), fit_df)

enter image description here

该软件包将打印NOTE,警告您请求的术语是高级交互的一部分。风险自负。我很确定这里的置信区间是渐近的。