On Fri, Apr 22, 2011 at 7:08 AM, Cliff Clive <cliffcl...@gmail.com> wrote: > I've been reading some code from an example in a blog post ( > http://www.maxdama.com/ here ) and I came across an operator that I hadn't > seen before. The author used a <<- operator to update a variable, like so: > > ecov_xy <<- ecov_xy+decay*(x[t]*y[t]-ecov_xy) > > At first I thought it was a mistake and tried replacing it with the usual <- > assignment operator, but I didn't get the same results. So what does the > double arrow <<- operator do?
It's the 'superassignment' operator. It does the assignment in the enclosing environment. That is, starting with the enclosing frame, it works its way up towards the global environment until it finds a variable called ecov_xy, and then assigns to it. If it never finds an existing ecov_xy it creates one in the global environment. The good use of superassignment is in conjuction with lexical scope, where an environment stores state for a function or set of functions that modify the state by using superassignment. make.accumulator<-function(){ a<-0 function(x) { a<<-a+x a } } > f<-make.accumulator() > f(1) [1] 1 > f(1) [1] 2 > f(11) [1] 13 > f(11) [1] 24 The Evil and Wrong use is to modify variables in the global environment. -thomas -- Thomas Lumley Professor of Biostatistics University of Auckland ______________________________________________ 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.