[R] vectorization & modifying globals in functions

Suzen, Mehmet msuzen at gmail.com
Thu Dec 27 22:39:04 CET 2012


You can use environments. Have a look at this this discussion.

http://stackoverflow.com/questions/7439110/what-is-the-difference-between-parent-frame-and-parent-env-in-r-how-do-they

On 27 December 2012 21:38, Sam Steingold <sds at gnu.org> wrote:
> I have the following code:
>
> --8<---------------cut here---------------start------------->8---
> d <- rep(10,10)
> for (i in 1:100) {
>   a <- sample.int(length(d), size = 2)
>   if (d[a[1]] >= 1) {
>     d[a[1]] <- d[a[1]] - 1
>     d[a[2]] <- d[a[2]] + 1
>   }
> }
> --8<---------------cut here---------------end--------------->8---
>
> it does what I want, i.e., modified vector d 100 times.
>
> Now, if I want to repeat this 1e6 times instead of 1e2 times, I want to
> vectorize it for speed, so I do this:
>
> --8<---------------cut here---------------start------------->8---
> update <- function (i) {
>   a <- sample.int(n.agents, size = 2)
>   if (d[a[1]] >= delta) {
>     d[a[1]] <- d[a[1]] - 1
>     d[a[2]] <- d[a[2]] + 1
>   }
>   entropy(d, unit="log2")
> }
> system.time(entropy.history <- sapply(1:1e6,update))
> --8<---------------cut here---------------end--------------->8---
>
> however, the global d is not modified, apparently update modifies the
> local copy.
>
> so,
> 1. is there a way for a function to modify a global variable?
> 2. how would you vectorize this loop?
>
> thanks!
>
> --
> Sam Steingold (http://sds.podval.org/) on Ubuntu 12.04 (precise) X 11.0.11103000
> http://www.childpsy.net/ http://honestreporting.com
> http://pmw.org.il http://www.PetitionOnline.com/tap12009/
> A number problem "solved" with floats turns into 1.9999999999999998 problems.
>
> ______________________________________________
> R-help at 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.




More information about the R-help mailing list