0

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?

M--
  • 25,431
  • 8
  • 61
  • 93
Beginner Java
  • 65
  • 1
  • 8

1 Answers1

1

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.

M--
  • 25,431
  • 8
  • 61
  • 93
  • As I understand you, you want to do all your code at once. So, I built my function to you but since I cannot access your data I get an error. I will pass you my code and just replace your code in and see if it is work or not. –  May 03 '17 at 16:13