线性回归 - 移动每个 运行 的独立列和相关列

Linear regression - moving independent and dependent columns for each run

我正在努力解决这个问题:

假设我有 data("mtcars") 数据框。我想对该数据框的两列进行回归(例如 mtcars$mpgmtcars$wt),将每个回归的 R 平方和每个回归的残差存储到两个不同的数据框中,然后将列移动到对自变量和因变量都是正确的(例如 mtcars$cylmtcars$qsec)。我需要重复这个直到我到达最后一个自变量列(在这个 mtcars 数据库中它将是 drat 列)。

如有任何帮助,我们将不胜感激!

对列索引使用滚动应用。 List(c(-5, 0)) 表示在每次迭代中使用偏移量 -5 和 0。

library(zoo)

resids <- t(rollapply(1:ncol(mtcars), list(c(-5, 0)), 
  function(ix) resid(lm(mtcars[, ix]))))

rsquareds <- rollapply(1:ncol(mtcars), list(c(-5, 0)), 
  function(ix) summary(lm(mtcars[, ix]))$r.squared)

如果您想反转因变量和自变量,请改用 list(c(0, -5))