[R-sig-hpc] nested foreach loop
Simon Urbanek
simon.urbanek at r-project.org
Thu Feb 4 20:13:27 CET 2016
On Feb 4, 2016, at 10:12 AM, aisha at mun.ca wrote:
> Hello,
>
> When I run this simple example of nested foreach loop:
>
> foreach(i=1:3, .packages="foreach") %dopar% {
> + foreach(j=1:3) %dopar% {
> + y=sqrt(i+j)
> + }
> + }
> I get
>
> [[1]]
> [[1]][[1]]
> [1] 1.414214
>
> [[1]][[2]]
> [1] 1.732051
>
> [[1]][[3]]
> [1] 2
>
>
> [[2]]
> [[2]][[1]]
> [1] 1.732051
>
> [[2]][[2]]
> [1] 2
>
> [[2]][[3]]
> [1] 2.236068
>
> [[3]]
> [[3]][[1]]
> [1] 2
>
> [[3]][[2]]
> [1] 2.236068
>
> [[3]][[3]]
> [1] 2.44949
>
>
>> y
> [1] 1.000000 1.414214 1.732051
>
> Why y gives [1] 1.000000 1.414214 1.732051
> 1.000000 is not even a correct value for y=sqrt(i+j)
> and why y is a vector in the first place?
>
You cannot have side-effects (like y=...) in parallel code, obviously, so the above doesn't make sense. You can only return values from parallel code since, by definition, it is called independently in parallel. In fact the above doesn't even touch y, so you're printing whatever you set y to in your global environment before.
Cheers,
Simon
> _______________________________________________
> R-sig-hpc mailing list
> R-sig-hpc at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-hpc
>
More information about the R-sig-hpc
mailing list