首页 > 解决方案 > 如何为每个回归循环迭代向数据集添加新列?

问题描述

我试图通过将观察结果分成 1/4 组和 3/4 组(分别为测试和训练)来测试模型的预测能力,使用自变量训练样本运行一阶回归,使用这些系数产生来自自变量测试样本的预测值,然后我想将这些预测值的新列添加到循环的每次迭代的因变量测试数据中。

对于上下文:TSIP500 是完整样本;iv是自变量;dv是因变量,最多 50 次迭代只是一个迭代次数不太大的测试。

我在使用 predict 函数时遇到问题,所以我手动完成了方程。我的代码如下:

for(i in 1:50){
  test_index <- sample(nrow(TSIP500iv), (1/4)*nrow(TSIP500iv), replace=FALSE)
  train_500iv <- TSIP500[-test_index,"distance"]
  test_500iv <- TSIP500[test_index,"distance"]
  train_500dv <- TSIP500[-test_index,"percent_of_max"]
  test_500dv <- TSIP500[test_index,"percent_of_max"]
  reg_model <- lm(train_500dv~train_500iv)
  int <- reg_model$coeff[1]
  B1 <- reg_model$coeff[2]
  predicted <- (int + B1*test_500iv)
  predicted <- data.frame(predicted)
  test_500dv <- data.frame(test_500dv)
  test_500dv[,i] <- apply(predicted)
}

我为最后一行尝试了不同的方法,但我总是只添加一个单列。任何帮助将不胜感激。

标签: rloopsmultiple-columnsadd

解决方案


for(i in 1:50){
  test_index <- sample(nrow(TSIP500iv), (1/4)*nrow(TSIP500iv), replace=FALSE)
  train_500iv <- TSIP500[-test_index,"distance"]
  test_500iv <- TSIP500[test_index,"distance"]
  train_500dv <- TSIP500[-test_index,"percent_of_max"]
  test_500dv <- TSIP500[test_index,"percent_of_max"]
  reg_model <- lm(train_500dv~train_500iv)
  int <- reg_model$coeff[1]
  B1 <- reg_model$coeff[2]
  temp_results <- paste('pred',i,sep='_')
  assign(temp_results, as.data.frame(int + B1*test_500iv))
  test_500dv <- cbind(data.frame(test_500dv),temp_results)
}

推荐阅读