gpt4 book ai didi

r - 理解 foreach

转载 作者:行者123 更新时间:2023-12-01 01:44:25 24 4
gpt4 key购买 nike

我是使用 foreach 并行 for 循环的新手,并且很难理解它是如何工作的。作为练习的示例,我创建了一个基于数据框 (input) 的简单列表 (input2)。我尝试通过循环 h 和 j 来计算 b。

library(doParallel)
library(foreach)
library(dplyr)

input <- data.frame(matrix(rnorm(200*200, 0, .5), ncol=200))
input[input <=0] =0
input['X201'] <- seq(from = 0, to = 20, length.out = 10)
input <- input %>% select(c(X201, 1:200))
input2 <- split(input, f= input$X201)

a = 0
b= 0
cl <- parallel::makeCluster(20)
doParallel::registerDoParallel(cl)
tm1 <- system.time(
y <-
foreach (h = length(input2),.combine = 'cbind') %:%
foreach (j = nrow(input2[[h]]),.combine = 'c',packages = 'foreach') %dopar%{
a = input2[[h]][j,3]
b = b + a
}

)
parallel::stopCluster(cl)
registerDoSEQ()
print("Cluster stopped.")

y 是关于 0.55 (确切值取决于生成的随机数),即 input2[[10]][20,3] 的值,不是我想要的累计值。我检查了 foreach 包的手册,但仍然不确定我是否完全理解 foreach 函数的机制。

最佳答案

R foreach 返回结果而是允许更改外部变量。所以不要指望 a, b 正确更新。

尝试以下

cl <- parallel::makeCluster(20)
doParallel::registerDoParallel(cl)

tm2 <- system.time(
results <- foreach(h = (1:length(input2)), .combine = "c") %dopar%{
sum( input2[[h]][1:nrow(input2[[h]]),3])
},
b <- sum(results[1:length(results)])
)
parallel::stopCluster(cl)
registerDoSEQ()
b
tm2

关于r - 理解 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52785027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com