我正试图在R中创建一个简单的for循环,但我不确定如何在不创建全局变量的情况下去做这件事。如何声明R中的for循环
我想输出一个预测表整齐地,而不是通过我希望预测的许多不同的实例(如下图)运行代码。
house1 = newdata[1,]
predict(fullmodel, house1)
predict(sqftmodel, house1)
predict(bestmodel, house1)
house2 = newdata[2,]
predict(fullmodel, house2)
predict(sqftmodel, house2)
predict(bestmodel, house2)
house3 = newdata[3,]
我想使用for循环来运行37个不同的房子,并在表中输出。有任何想法吗?
编辑:这是迄今为止一个我的代码部分
data = read.table("DewittData.txt")
newdata = na.omit(data)#28 points to refer to
colnames(newdata) = c("ListPrice", "Beds", "Bath","HouseSize","YearBuilt"
,"LotSize", "Fuel","ForcedAir", "Other","FM","ESM","JD",
"SchoolDistrict","HouseType","GarageStalls","Taxes")
attach(newdata)
fullmodel = lm((ListPrice) ~ HouseSize + Beds + Bath + YearBuilt + LotSize
+ Fuel + ForcedAir + Other + SchoolDistrict+
HouseType + Other + FM + ESM + JD + GarageStalls + Taxes)
bestmodel = lm(ListPrice~Beds)
sqftmodel = lm(ListPrice~HouseSize, data = newdata)
更新:
我明白了,所以我把它改成
predict(fullmodel, newdata[,])
predict(sqftmodel, newdata[,])
predict(bestmodel, newdata[,])
现在我将如何输出这在表格格式?
解决你的问题的一种方法是建立你的功能。或者可以使用“应用”功能。 – Alice
您可以直接将整个数据框传递给'predict()',不需要逐行传递行 –
@BeginnerJava使用'dput'来创建一个可重复使用的数据集示例。 – Masoud