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

______________________________________________
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.

Reply via email to