R for loop n times

Tarzan picture Tarzan · Nov 18, 2017 · Viewed 11.6k times · Source

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

Answer

dww picture dww · Nov 18, 2017

The confusion is that when you execute just a name as a statement (e.g. in your statement TSR) it normally prints the value of that object to the console. However, inside a loop this default printing is suppressed. You will need to print it explicitly with print(TSR).

We can see this behaviour in a simpler example. First try this

for (i in 1:100) i 

then try this

for (i in 1:100) print(i)

That explains why you don't see anything printed. But why no plot? Because the loop exits on a break before getting there. This will always happen because you first set TSR0 = TSR, then you break if TSR - TSR0 (which now equals zero by definition) is less than delta. I think you need to set TSR0 = TSR only after testing the difference between them, not before.