简体   繁体   English

R中简单线性回归和预测的迭代

[英]Iteration for Simple Linear Regression and Prediction in R

Using R, I would like to run n iterations for generating n simple linear regression models using a training dataset to predict n sets of fitted values for the test data.使用 R,我想运行n次迭代来生成n 个简单的线性回归模型,使用训练数据集来预测测试数据的n组拟合值。 This would involve storing the models and predictions in appropriate containers.这将涉及将模型和预测存储在适当的容器中。 I would also like to label the predictions using a vector of labels.我还想使用标签向量来标记预测。 The data are structured as follows: X = c(1.1,2.3,3.4,4.5,5.8), Y = c(1.0,2.4,3.3,4.7,6.0) and the model would be like lm(Y.train~X.train) and the predictions would be like predict(lm, data = test_set) .数据结构如下: X = c(1.1,2.3,3.4,4.5,5.8), Y = c(1.0,2.4,3.3,4.7,6.0)模型类似于lm(Y.train~X.train)并且预测将类似于predict(lm, data = test_set) How would I set this up?我该如何设置? Is there a better approach?有没有更好的方法?

Thanks!谢谢!

Set up a list or two to store the fitted model and the predictions.设置一两个列表来存储拟合模型和预测。 Then loop.然后循环。

In the code below, you'll need to fill in the ...'s since I don't know what your data look like or how you are deciding what will differ between each iteration.在下面的代码中,您需要填写...,因为我不知道您的数据是什么样的,也不知道您如何决定每次迭代之间会有什么不同。

model_list   <- vector(mode="list", length=N)
predict_list <- vector(mode="list", length=N)

for (i in 1:N) {
    # fit model
    model_list[[i]] <- lm(y ~ x, data=subset(...))

    # store predictions
    predict_list[[i]] <- predict(model_list[[i]], newdata=subset(...))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM