Skip to content
Prev 176094 / 398503 Next

Nice error from misuse of <- and <<-

Here's a simplified version of some code I wrote for a demonstration.  I 
wanted a function that was attached to a tck/tk button to redo a 
simulation on request; then some plots were changed, etc.  But it didn't 
work on the first attempt:


 > x <- NULL
 > xmean <- NULL
 >
 > resim <- function() {
+   x <- rnorm(100)
+   x <<- x^2           # assign to global x
+   xmean <<- mean(x)   # assign to global xmean
+ }
 >
 > resim()
 > mean(x)
[1] 1.059142
 > xmean
[1] 0.1273437

Why aren't mean(x) and xmean the same?  If you want to work it out 
yourself, don't scroll down ....










The two values are not the same because my resim function's first line 
created a local variable x, and that's the one whose mean is stored in 
xmean, not the mean of the global x.  I should have used a different 
name for the local variable, or done all my assignments to the global one.

Duncan Murdoch