通过cbind(y0, y1, y2, y3, y4, y5, y6)
我们拟合 7 个独立模型(这是一个更好的主意)。
对于您要查找的内容,堆叠您的y*
变量,复制其他自变量并进行一次回归。
Y <- c(y0, y1, y2, y3, y4, y5, y6)
tt. <- rep(tt, times = 7)
tcb. <- rep(tcb, times = 7)
s. <- rep(s, times = 7)
l. <- rep(l, times = 7)
b. <- rep(b, times = 7)
fit <- lm(Y ~ tt. + tcb. + s. + l. + b.)
的预测值y*
是
matrix(fitted(fit), ncol = 7)
对于 OP 以外的其他读者
我在此准备了一个可重复的小例子(只有一个协变量x
和两个重复y1
)y2
来帮助你消化这个问题。
set.seed(0)
dat_wide <- data.frame(x = round(runif(4), 2),
y1 = round(runif(4), 2),
y2 = round(runif(4), 2))
# x y1 y2
#1 0.90 0.91 0.66
#2 0.27 0.20 0.63
#3 0.37 0.90 0.06
#4 0.57 0.94 0.21
## The original "mlm"
fit_mlm <- lm(cbind(y1, y2) ~ x, data = dat_wide)
而不是做c(y1, y2)
and rep(x, times = 2)
,我会使用reshape
R base package 中的函数stats
,因为这样的操作本质上是一个“宽”到“长”的数据集重塑。
dat_long <- stats::reshape(dat_wide, ## wide dataset
varying = 2:3, ## columns 2:3 are replicates
v.names = "y", ## the stacked variable is called "y"
direction = "long" ## reshape to "long" format
)
# x time y id
#1.1 0.90 1 0.91 1
#2.1 0.27 1 0.20 2
#3.1 0.37 1 0.90 3
#4.1 0.57 1 0.94 4
#1.2 0.90 2 0.66 1
#2.2 0.27 2 0.63 2
#3.2 0.37 2 0.06 3
#4.2 0.57 2 0.21 4
额外的变量time
和id
被创建。前者告诉一个案例来自哪个复制品;后者告诉哪个记录该案例在复制中。
为了对所有重复拟合相同的模型,我们做
fit1 <- lm(y ~ x, data = dat_long)
#(Intercept) x
# 0.2578 0.5801
matrix(fitted(fit1), ncol = 2) ## there are two replicates
# [,1] [,2]
#[1,] 0.7798257 0.7798257
#[2,] 0.4143822 0.4143822
#[3,] 0.4723891 0.4723891
#[4,] 0.5884029 0.5884029
不要惊讶两列是相同的;毕竟,两个重复只有一组回归系数。
如果您仔细考虑,我们可以改为执行以下操作:
dat_wide$ymean <- rowMeans(dat_wide[2:3]) ## average all replicates
fit2 <- lm(ymean ~ x, data = dat_wide)
#(Intercept) x
# 0.2578 0.5801
我们将得到相同的点估计。由于两个模型具有不同的样本量,标准误差和其他汇总统计量会有所不同。
coef(summary(fit1))
# Estimate Std. Error t value Pr(>|t|)
#(Intercept) 0.2577636 0.2998382 0.8596755 0.4229808
#x 0.5800691 0.5171354 1.1216967 0.3048657
coef(summary(fit2))
# Estimate Std. Error t value Pr(>|t|)
#(Intercept) 0.2577636 0.01385864 18.59949 0.002878193
#x 0.5800691 0.02390220 24.26844 0.001693604