foreach 和 dopar 返回 NULL 而不是所需的答案
foreach and dopar returning NULL instead of the desired answer
以下函数按需要并行执行,但 returns NULL
而不是预期的矩阵。我做错了什么?
doTheMath_MC <- function(st, end, nd) {
if (st > end) stop("end must be larger than st")
print(getDoParWorkers())
# Helper function from whosebug.com/a/23158178/633251
tr <- function(x, prec = 0) trunc(x * 10^prec) / 10^prec
# Helper function to use with foreach
fef <- function(i, j, num, trpi) {
if (num[j] >= num[i]) return(NULL)
val <- num[i]/num[j]
if (!tr(val, nd) == trpi) return(NULL)
return(c(i, j, tr(val, nd)))
}
# Here we go...
nd <- nd - 1
trpi <- tr(pi, nd)
num <- st:end
ni <- length(num)
ans <- foreach(i = 1:ni, .combine = rbind) %dopar% {
tmp <- matrix(NA_real_, ncol = 3)
for (j in 1:ni) {
tmp <- rbind(tmp, fef(i, j, num, trpi))
} # The backend holds all the results until all are done
} #end of dopar control
str(ans) # NULL ! Why?
cat("Done computing", paste("EST", st, end, nd+1, sep = "_"), "\n")
if (is.null(ans)) return(NULL)
ans <- as.matrix(na.omit(ans)) # probably not needed in MC version
return(ans) # c("num", "den", "est", "eff")
}
你能尝试从 foreach
循环显式返回一个值吗?:
ans <- foreach(i = 1:ni, .combine = rbind) %dopar% {
tmp <- matrix(NA_real_, ncol = 3)
for (j in 1:ni) {
tmp <- rbind(tmp, fef(i, j, num, trpi))
}
return(tmp) # explicitly return the matrix tmp
}
以下函数按需要并行执行,但 returns NULL
而不是预期的矩阵。我做错了什么?
doTheMath_MC <- function(st, end, nd) {
if (st > end) stop("end must be larger than st")
print(getDoParWorkers())
# Helper function from whosebug.com/a/23158178/633251
tr <- function(x, prec = 0) trunc(x * 10^prec) / 10^prec
# Helper function to use with foreach
fef <- function(i, j, num, trpi) {
if (num[j] >= num[i]) return(NULL)
val <- num[i]/num[j]
if (!tr(val, nd) == trpi) return(NULL)
return(c(i, j, tr(val, nd)))
}
# Here we go...
nd <- nd - 1
trpi <- tr(pi, nd)
num <- st:end
ni <- length(num)
ans <- foreach(i = 1:ni, .combine = rbind) %dopar% {
tmp <- matrix(NA_real_, ncol = 3)
for (j in 1:ni) {
tmp <- rbind(tmp, fef(i, j, num, trpi))
} # The backend holds all the results until all are done
} #end of dopar control
str(ans) # NULL ! Why?
cat("Done computing", paste("EST", st, end, nd+1, sep = "_"), "\n")
if (is.null(ans)) return(NULL)
ans <- as.matrix(na.omit(ans)) # probably not needed in MC version
return(ans) # c("num", "den", "est", "eff")
}
你能尝试从 foreach
循环显式返回一个值吗?:
ans <- foreach(i = 1:ni, .combine = rbind) %dopar% {
tmp <- matrix(NA_real_, ncol = 3)
for (j in 1:ni) {
tmp <- rbind(tmp, fef(i, j, num, trpi))
}
return(tmp) # explicitly return the matrix tmp
}