我进行了多级回归,现在有一个系数矩阵,包括回归中每个组(=因子变量)的值+标准误差,例如:我的矩阵(用于拦截+一个名为Beta1
的变量)看起来像这样:
Group Intercept Beta1 Intercept.se Beta1.se
11 0.044357458 0.4381340 0.08358735 0.1572632
12 -0.007072542 0.1242737 0.09317142 0.1643544
21 0.021075871 0.3727055 0.12050036 0.2459456
22 0.023895981 0.6786013 0.11207848 0.3188887
31 -0.115713481 0.3547718 0.09760681 0.1454787
32 -0.004081244 -0.1954594 0.09993201 0.1953406
我想要实现的是绘制一个图表,显示每个组的可能回归线。我想出了以下代码,每组生成15行(coef.mtx
是上面提到的矩阵):
for (i in 1:6) { # we have 6 groups
x = coef.mtx[i,]
lines[(i*6-5):(i*6),] =
list(Group = replicate(15, x["Group"]),
int = replicate(15, rnorm(1,x["Intercept"],x["Intercept.se"])),
slo = replicate(15, rnorm(1, x["Beta1"], x["Beta1.se"])))
}
这会生成如下数据框:
Group int slo
1 11 0.09484568 0.3005997
2 11 0.12364749 0.5758899
3 11 -0.02942938 0.4821841
4 11 0.17226587 0.2413752
5 11 0.02923023 0.4251419
6 11 0.14650632 0.4541752
7 12 0.06784996 0.0356669
8 12 -0.02832304 0.2214471
...
然后我可以用这样的ggplot绘制这些行:
ggplot(myData, aes(x=Beta1, y=Outcome)) +
geom_jitter() +
facet_wrap(~ Group) +
geom_abline(aes(intercept=int, slope=slo), data=lines)
最终结果如下:
有没有更好的方法来转换系数矩阵而不是使用这个循环?我无法想到更好的方法......或者:你如何看待可能的回归线(而不仅仅是点估计)?