[R] Nice error from misuse of <- and <<-
Duncan Murdoch
murdoch at stats.uwo.ca
Sat Apr 4 17:02:21 CEST 2009
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
More information about the R-help
mailing list