r - 如何为每个回归循环迭代向数据集添加新列?
问题描述
我试图通过将观察结果分成 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)
}
我为最后一行尝试了不同的方法,但我总是只添加一个单列。任何帮助将不胜感激。
解决方案
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)
}
推荐阅读
- php - 从 csv 文件中删除一些行数
- excel - 计算进度条百分比
- c# - BrowseFolderDialog - 这会破坏 MVVM 吗?
- python-3.x - docker-compose 找不到文件
- python - 带有行内标签的Python plotly_Connection标记
- ios - 如何在 Objective-C 中更改 QR 码的颜色?
- python - 正则表达式 - 在符号后查找数字
- azure-cognitive-search - Azure 认知搜索标准 Lucene 分析器通配符和模糊搜索问题
- c# - c# - 如何从 objectName 创建 Generic T?
- tabulator - 您如何访问或确定设置/需要哪些 Tabulator 参数