I'm trying to write a for loop to repeat (c) and (d) 100 times. I want to print the estimates of TRS-TRS0 at each iteration of the for loop. It should stop algorithm if it is small (say 1/10000). Finally I want it to create a plot in which each of these values is displayed.
I think I have everything here, but when I run it I don't see anything happen. Am I missing something?
for (i in 1:100){
#c)
fit1 = loess(res~x2, data=data.frame(res,x1,x2))
f2=predict(fit1,newdata=data.frame(res,x1,x2))
res=data$y-mean(data$y) -f2
#d)
fit2 = loess(res~x1, data=data.frame(res,x1,x2))
f1=predict(fit2,newdata=data.frame(res,x1,x2))
res=data$y - mean(data$y)-f1
TSR=sum((data$y-mean(data$y)-f1-f2)^2);TSR
if (abs(TSR-TSR0) > delta) TSR0=TSR else break
#continue
if (abs(TSR-TSR0) < delta) break
TSR0=TSR
val=TSR-TSR0;val
x11(); plot(x1,f1); plot(x2,f2)
}
To reproduce, here is the created data:
set.seed(3)
x1=runif(300);x2=runif(300)
error=rnorm(300,mean=0,sd=3)
z1=-2+3*x1; z2=2*sin(2*pi*x2)
data=data.frame(x1,x2,y=z1+z2+error)
#fit the model
TSR0=0
f10=0;f20=0
res=data$y-mean(data$y) -f10 -f20;
delta=.0001