Reputation: 75
I am trying to create a simple for loop in R, but I am not sure how to go about this without creating a global variable.
I am trying to output a predict table neatly, instead of running code through many different instances (something like below) that I wish to predict.
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,]
I want to use a for loop to run through 37 different houses and have the output in a table. Any ideas?
edit: this is a portion of my code so far
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)
update:
I see, so I've changed it to
predict(fullmodel, newdata[,])
predict(sqftmodel, newdata[,])
predict(bestmodel, newdata[,])
Now how would I output this in a table format?
Upvotes: 0
Views: 99
Reputation: 28826
I am not sure if I get your question , but this what I would do for predicting based on different rows of a df
.
Housefull <- predict(fullmodel, newdata[,])
Housebest <- predict(bestmodel, newdata[,])
Housesqft <- predict(sqftmodel, newdata[,])
Generally, sticking to vectors is much better than using loops.
Upvotes: 1