r语言 - 如何为每个回归循环迭代向数据集添加新列?



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

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

我在使用预测函数时遇到问题,所以我手动做了这个方程。我的代码如下:

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)
}

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

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)
}

最新更新