英文:
fixing foreach and dopar loop in R
问题
以下是您要翻译的内容:
"Following the previous posthere, I wrote a code in R, but it does not work.
What I want to do is to have multiple output of arrays with foreach
.
In Matlab, what I want to do is as follows. I want to have arrays X and Y by parellel computing.
X=zeros(2,5,10); Y=zeros(10,2); parfor i=1:10; X(:,:,i) = randn(2,5); Y(i,:) = randn(1,2); end
Based on the comments for the previous post, I wrote an R code as follows. But, this does not work. The problem seems to be around the definition of Z.
X <- array(0, dim = c(2,5,10)) Y <- array(0, dim = c(10,2)) Z <- foreach(i=1:10, .combine = 'c') %dopar% { Y_i <- i*c(1,2) X_i <- matrix(rnorm(10),2,5) Y[ i , ] <- Y_i X[ , , i] <- X_i Z <- list(Y, X) } ```
Any help would be much appreciated."
<details>
<summary>英文:</summary>
Following the previous post[here](https://stackoverflow.com/q/75479731/21230830), I wrote a code in R, but it does not work.
What I want to do is to have multiple output of arrays with `foreach`.
In Matlab, what I want to do is as follows. I want to have arrays X and Y by parellel computing.
X=zeros(2,5,10);
Y=zeros(10,2);
parfor i=1:10;
X(:,:,i) = randn(2,5);
Y(i,:) = randn(1,2);
end
Based on the comments for the previous post, I wrote an R code as follows. But, this does not work. The problem seems to be around the definition of Z.
rm(list=ls()) # clear all variables
library(foreach)
library(doParallel)
X <- array(0, dim = c(2,5,10))
Y <- array(0, dim = c(10,2))
Z <- foreach(i=1:10, .combine = 'c') %dopar% {
Y_i <- i*c(1,2)
X_i <- matrix(rnorm(10),2,5)
Y[ i , ] <- Y_i
X[ , , i] <- X_i
Z <- list(Y, X)
}
Any help would be much appreciated.
</details>
# 答案1
**得分**: 1
给定的代码几乎完成了。在循环内部,它涉及环境(参见优秀的解释:http://adv-r.had.co.nz/Environments.html)。因此,就像一个函数一样,它需要将 Z(局部环境)返回给 Z(全局环境)。
```R
rm(list=ls()) # 清除所有变量
library(foreach)
library(doParallel)
X <- array(0, dim = c(2,5,10))
Y <- array(0, dim = c(10,2))
Z <- foreach(i=1:10, .combine = 'c') %dopar% {
Y_i <- i*c(1,2)
X_i <- matrix(rnorm(10),2,5)
Y[ i , ] <- Y_i
X[ , , i] <- X_i
Z <- list(Y, X)
Z
}
英文:
The given code is almost done. Inside the loop, it is about environment (see the excellent explanation: http://adv-r.had.co.nz/Environments.html). Thus, like a function, it needs to return Z (local env) to Z (global env).
rm(list=ls()) # clear all variables
library(foreach)
library(doParallel)
X <- array(0, dim = c(2,5,10))
Y <- array(0, dim = c(10,2))
Z <- foreach(i=1:10, .combine = 'c') %dopar% {
Y_i <- i*c(1,2)
X_i <- matrix(rnorm(10),2,5)
Y[ i , ] <- Y_i
X[ , , i] <- X_i
Z <- list(Y, X)
Z
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论