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) 和 rep(x, times = 2),而是使用 R 基础包 stats 中的 reshape 函数,因为这样的操作本质上是从“宽”到“长”的数据集重塑。
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