R中多级分析中的绘图调节效应

时间:2016-09-20 11:06:21

标签: r plot multi-level

在我的数据集中,我有3个组,我想在y上绘制组和x之间的交互。

id <- c(1,1,1,2,2,2,3,3,3)
group <- c(0,0,0,1,1,1,2,2,2)
x <- c(20,50,30,50,65,80,20,50,60)
y <- c(120,130,150,200,210,180,160,170,120)

我已经尝试过&#34; interaction.plot&#34;但它没有用。

interaction.plot(x,group,y)

是否有人使用良好的R语法来绘制此交互?

1 个答案:

答案 0 :(得分:1)

无论您想要什么,都必须将class组更改为factor。确实interaction.plot()用于因素的双向组合,而您的x不是因素。但如果一个是连续的,interaction.plot()会提供一些帮助。在您的情况下,输出显示&#34;考虑与此类数据的交互是一个愚蠢的想法&#34;

但如果你想做(我想你想要一个线性模型):

df <- data.frame(id = id, x = x, y = y, group = as.factor(group))

## Base plot
model <- lm(y ~ x * group, data = df)
xpara <- 20:80

plot(y ~ x, data = df, col=c(2:4)[group], pch=19)
for(i in 1:3) lines(xpara, predict(model, data.frame(x = xpara, group = as.factor(i-1))), col = i+1)
legend("topleft",paste(c("group0","group1","group2")), pch=19, lty=1, col=c(2:4))

## ggplot2 (I plotted lines and confidence intervals to interpret)
library(ggplot2)
ggplot(df, aes(x = x, y = y, colour = group)) + 
  geom_point(size = 4) +
  geom_smooth(method = "lm", se = T, fullrange = T)

enter image description here

[编辑]

如果predict()支持的模型类,方式基本相同。

df2 <- data.frame(id = as.factor(id), x = x, y = y, group = as.factor(group))
library(nlme)

# first; make model
lme.mod <- lme(y ~ x * group, random = ~ 1|id, data = df2)

# second; get predicted values
xpara <- 20:80   # make a vector for an independent variable you use as x.
y.g1 <- predict(lme.mod, data.frame(x = xpara, group = "0", id = "1"), type="response")
y.g2 <- predict(lme.mod, data.frame(x = xpara, group = "1", id = "1"), type="response")
y.g3 <- predict(lme.mod, data.frame(x = xpara, group = "2", id = "1"), type="response")

# third; draw
plot(y ~ x, df2, col=c(2:4)[group], pch=19)
lines(xpara, y.g1, col=2)
lines(xpara, y.g2, col=3)
lines(xpara, y.g3, col=4)

## Simplificated version
lev <- levels(df$group)

plot(y ~ x, data = df2, col=c(2:4)[group], pch=19, ylab="y (id = "1")")
for(i in seq.int(length(lev))) 
  lines(xpara, predict(lme.mod, data.frame(x = xpara, group = lev[i], id = 1)), col = i+1)
legend("topleft",paste(c("group0","group1","group2")), pch=19, lty=1, col=c(2:4))