如何将“...”参数传递给从foreach()调用的函数?

时间:2022-06-01 19:03:49

The following code produces the warning:

以下代码生成警告:

Warning message:
<anonymous> : <anonymous>: ... may be used in an incorrect context: ‘mean(x[l], ...)’

doForeach <- function(x, ...)
{
    require(doSNOW)
    require(foreach)
    cl <- snow::makeCluster(2, type="MPI")
    on.exit(snow::stopCluster(cl))
    registerDoSNOW(cl)
    do.i <- function(i) lapply(seq_len(length(x)), function(l) mean(x[l], ...))
    foreach(i=seq_len(10)) %dopar% { do.i(i) }
}
x <- rnorm(20)
r <- doForeach(x, trim=1)

I'd guess that it comes from the fact that the workers/slaves do not see the ... anymore. Formal arguments are typically passed as character vectors via .export=c("<arg>"), but that does not seem to work for ... arguments.

我猜这是因为工人/奴隶不再看到......了。形式参数通常通过.export = c(“ ”)作为字符向量传递,但这似乎不适用于...参数。

What's the correct way of dealing with ... arguments in this example?

在这个例子中处理...参数的正确方法是什么?

1 个解决方案

#1


2  

Okay, apparently the ... arguments have to be passed via do.i. Here is a more obvious (and correctly running) example:

好吧,显然......论证必须通过do.i传递。这是一个更明显(并且正确运行)的示例:

doForeach <- function(x, ...)
{
    require(doSNOW)
    require(foreach)
    cl <- snow::makeCluster(2, type="MPI")
    on.exit(snow::stopCluster(cl))
    registerDoSNOW(cl)
    do.i <- function(i, ...) lapply(seq_len(length(x)), function(l) max(x[l], ...))
    foreach(i=seq_len(5)) %dopar% { do.i(i, ...) }
}
x <- 1:3
doForeach(x, 1.5)

#1


2  

Okay, apparently the ... arguments have to be passed via do.i. Here is a more obvious (and correctly running) example:

好吧,显然......论证必须通过do.i传递。这是一个更明显(并且正确运行)的示例:

doForeach <- function(x, ...)
{
    require(doSNOW)
    require(foreach)
    cl <- snow::makeCluster(2, type="MPI")
    on.exit(snow::stopCluster(cl))
    registerDoSNOW(cl)
    do.i <- function(i, ...) lapply(seq_len(length(x)), function(l) max(x[l], ...))
    foreach(i=seq_len(5)) %dopar% { do.i(i, ...) }
}
x <- 1:3
doForeach(x, 1.5)