On Dec 27, 2012, at 12:38 PM, Sam Steingold 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
}
}
In current versions of R the apply functions do not gain much (if any) in
speed over a well written for loop (the for loops are much more efficient
than they used to be).
Using global variables could actually slow things down a little for what
you are doing, if you use `<<-` then it has to search
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 wrote:
> I have the following code:
>
> --8<---cut here--
At Thu, 27 Dec 2012 15:38:08 -0500,
Sam Steingold wrote:
> so,
> 1. is there a way for a function to modify a global variable?
Use <<- instead of <-.
> 2. how would you vectorize this loop?
This is hard. Your function has a feedback loop: an iteration depends
on the previous iteration's result.
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
5 matches
Mail list logo