1

我想lm()在 R 中使用来拟合一系列(实际上是 93 个)单独的线性回归。根据 Rlm()帮助手册:

“如果响应是矩阵,则线性模型通过最小二乘法分别拟合到矩阵的每一列。”

只要 Y 响应矩阵中没有丢失的数据点,此方法就可以正常工作。当存在缺失点时,不是用可用数据拟合每个回归,而是丢弃在任何列中具有缺失数据点的每一行。有没有办法指定lm()应该独立地适合 Y 中的所有列,而不是丢弃单个列缺少数据点的行?

4

1 回答 1

4

如果您希望在 and 之间进行回归n,则不要指定 with而是应该使用 R 的apply 函数Y1, Y2, ..., YnXlm()

# create the response matrix and set some random values to NA
values <- runif(50)
values[sample(1:length(values), 10)] <- NA
Y <- data.frame(matrix(values, ncol=5))
colnames(Y) <- paste0("Y", 1:5)
# single regression term
X <- runif(10)

# create regression between each column in Y and X
lms <- lapply(colnames(Y), function(y) {
  form <- paste0(y, " ~ X")
  lm(form, data=Y)
})

# lms is a list of lm objects, can access them via [[]] operator
# or work with it using apply functions once again
sapply(lms, function(x) {
  summary(x)$adj.r.squared
})
#[1] -0.06350560 -0.14319796  0.36319518 -0.16393125  0.04843368
于 2012-09-18T16:49:44.850 回答