> -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] > On Behalf Of zhiji19 > Sent: Tuesday, November 09, 2010 12:02 AM > To: r-help@r-project.org > Subject: [R] Help with Iterator > > > Dear Experts, > > The following is my "Iterator". When I try to write a new function with > itel, I got error. > > This is what I have: > > supDist<-function(x,y) return(max(abs(x-y))) > > > > myIterator <- function(xinit,f,data=NULL,eps=1e-6,itmax=5,verbose=FALSE) > { > + xold<-xinit > + itel<-0 > + repeat { > + xnew<-f(xold,data) > + if (verbose) { > + cat( > + "Iteration: ",formatC(itel,width=3, format="d"), > + "xold: ",formatC(xold,digits=8,width=12,format="f"), > + "xnew: ",formatC(xnew,digits=8,width=12,format="f"), > + "\n" > + ) > + } > + if ((supDist(xold,xnew) < eps) || (itel == itmax)) { > + return(xnew) > + } > + xold<-xnew; itel<-itel+1 > + } > + } > > > mat<-function (x, data=NULL) {return (1+x^itel)} > > myIterator(3, f=mat, verbose=TRUE) > Error in f(xold, data) : object 'itel' not found > > > Can anyone please help me to fix the error?
It appears to me that your problem is a matter of variable "scope". The error message says that the function f cannot find object 'itel'. That is because itel is defined in the function iterate and is local to that function. You might want to add a third parameter to function f so you can pass in the value of itel. (I would avoid using itel for the parameter name as you will likely end up confusing yourself at some point). I haven't tried to figure out what you are doing so I don't know if that is the best solution. But the problem is that f doesn't know about object 'itel'. Hope this is helpful, Dan Daniel Nordlund Bothell, WA USA ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.