我正在尝试并行化我拥有的 for 循环。有问题的循环中有一个嵌套循环,我想并行化。答案肯定与: nested foreach loops in R to update common array非常相似,但我似乎无法让它工作。我已经尝试了所有我能想到的选项,包括只是将内部循环变成它自己的函数并将其并行化,但我不断得到空列表。
第一个非 foreach 示例有效:
theFrame <- data.frame(col1=rnorm(100), col2=rnorm(100))
theVector <- 2:30
regFor <- function(dataFrame, aVector, iterations)
{
#set up a blank results matrix to save into.
results <- matrix(nrow=iterations, ncol=length(aVector))
for(i in 1:iterations)
{
#set up a blank road map to fill with 1s according to desired parameters
roadMap <- matrix(ncol=dim(dataFrame)[1], nrow=length(aVector), 0)
row.names(roadMap) <- aVector
colnames(roadMap) <- 1:dim(dataFrame)[1]
for(j in 1:length(aVector))
{
#sample some of the 0s and convert to 1s according to desired number of sample
roadMap[j,][sample(colnames(roadMap),aVector[j])] <- 1
}
temp <- apply(roadMap, 1, sum)
results[i,] <- temp
}
results <- as.data.frame(results)
names(results) <- aVector
results
}
test <- regFor(theFrame, theVector, 2)
但是这个和我的其他类似尝试都行不通。
trying <- function(dataFrame, aVector, iterations, cores)
{
registerDoMC(cores)
#set up a blank results list to save into. i doubt i need to do this
results <- list()
foreach(i = 1:iterations, .combine="rbind") %dopar%
{
#set up a blank road map to fill with 1s according to desired parameters
roadMap <- matrix(ncol=dim(dataFrame)[1], nrow=length(aVector), 0)
row.names(roadMap) <- aVector
colnames(roadMap) <- 1:dim(dataFrame)[1]
foreach(j = 1:length(aVector)) %do%
{
#sample some of the 0s and convert to 1s according to desired number of sample
roadMap[j,][sample(colnames(roadMap),aVector[j])] <- 1
}
results[[i]] <- apply(roadMap, 1, sum)
}
results
}
test2 <- trying(theFrame, theVector, 2, 2)
我认为无论如何我都必须在内循环上使用 foreach ,对吗?