【问题标题】:How do I add new columns to a data set for each regression loop iteration?如何为每个回归循环迭代向数据集添加新列?
【发布时间】:2019-09-20 17:58:58
【问题描述】:

我正在尝试通过将观察结果分成 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)
}

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

【问题讨论】:

  • 请展示一个可重现的小例子
  • 如果没有样本数据(如 akrun 建议的那样),真的很难为您提供帮助。但是,看到 apply(predicted) 不仅仅意味着数据的逻辑组织(apply 具有三个必需的参数,您缺少 MARGIN=FUN=)。

标签: r loops multiple-columns add


【解决方案1】:
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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2021-02-02
    • 1970-01-01
    • 2019-08-13
    • 2017-09-05
    • 2018-06-13
    • 2019-06-09
    相关资源
    最近更新 更多