本文介绍了R嵌套的foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个输入数据集:
# environment
require(pacman)
p_load(
data.table
, doParallel
, foreach
)
doParallel::registerDoParallel(makeCluster(4))
# create input
runDT <- data.table(run = c(F,T,F,T)
, input1 = 1:4
, run_id = 1:4)
print(runDT)
run input1 run_id
1: FALSE 1 1
2: TRUE 2 2
3: FALSE 3 3
4: TRUE 4 4
这是另一个原始数据集:
and this is another raw dataset:
dataDT <- data.table(
ID = 1:4
, c1 = c(1:4))
print(dataDT)
ID c1
1: 1 1
2: 2 2
3: 3 3
4: 4 4
我想运行嵌套的foreach循环,但这给了我一个错误:
I would like to run nested foreach loops, but it's giving me an error:
# run
row_run <- runDT[run == T, run_id]
resultsDT <- foreach::foreach(
k = 1:length(row_run), .inorder = FALSE, .packages = c("data.table")) %dopar% {
# get the input for this run
inputDT <- runDT[run_id == row_run[k],]
# apply the input for all dataDT rows
result_run <- foreach::foreach(
j = 1:nrow(dataDT), .inorder = FALSE, .packages = c("data.table")) %dopar% {
dataDT_run <- dataDT[ID == j,]
dataDT_run[, c("o1", "run_id") := list(
c1 + inputDT[, input1]
, inputDT[, run_id]
)]
return(dataDT_run[, c("o1", "run_id"), with = FALSE])
}
result_run <- rbindlist(result_run)
return(result_run)
}
Error in { : task 1 failed - "could not find function "%dopar%""
resultsDT <- rbindlist(resultsDT)
print(resultsDT)
我希望看到的结果是:
resultsDT <- data.table(
o1 = c((1:4) + 2,c(1:4) + 4)
, run_id = c(rep(2,4),rep(4,4))
)
print(resultsDT)
o1 run_id
1: 3 2
2: 4 2
3: 5 2
4: 6 2
5: 5 4
6: 6 4
7: 7 4
8: 8 4
然后,我将第一个%dopar%
更改为%:%
,但出现了另一个错误:
Then I changed the first %dopar%
to %:%
, but it's giving another error:
Error in foreach::foreach(k = 1:length(row_run), .inorder = FALSE, .packages = c("data.table")) %:% :
no function to return from, jumping to top level
如何解决?
推荐答案
我会回答您的其他问题
doParallel::registerDoParallel(makeCluster(4))
当您创建4个集群时,runDT将复制到您的4个集群中.
As you make 4 cluster, runDT will copied into your 4 cluster.
inputDT <- runDT[run_id == row_run[k],]
另外,假设 k * j
为8,并且所有 inputDT
大小均为 100MB
.
Additionally, assume k*j
as 8 and all the inputDT
sizes are 100MB
.
size(Cluster1) : runDT + inputDT(100MB) + inputDT(100MB) + etc
size(Cluster2) : runDT + inputDT(100MB) + inputDT(100MB) + etc
size(Cluster3) : runDT + inputDT(100MB) + inputDT(100MB) + etc
size(Cluster4) : runDT + inputDT(100MB) + inputDT(100MB) + etc
这篇关于R嵌套的foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!