在函数中使用sfApply时的范围问题(包降雪 - R)

Jor*_*eys 5 r function scoping

让我在R中添加另一个范围问题,这次是降雪包.如果我在我的全局环境中定义一个函数,并且我稍后在另一个函数中的sfApply()中尝试使用该函数,则不再找到我的第一个函数:

#Runnable code. Don't forget to stop the cluster with sfStop()
require(snowfall)
sfInit(parallel=TRUE,cpus=3)

func1 <- function(x){
    y <- x+1
    y
}

func2 <- function(x){
    y <- sfApply(x,2,function(i) func1(i) )
    y
}

y <- matrix(1:10,ncol=2)
func2(y)
sfStop()
Run Code Online (Sandbox Code Playgroud)

这给出了:

> func2(y)
Error in checkForRemoteErrors(val) : 
  2 nodes produced errors; first error: could not find function "func1"
Run Code Online (Sandbox Code Playgroud)

如果我将我的函数嵌套在另一个函数中,它可以工作.当我在全局环境中使用sfApply()时,它也可以工作.事实是,我不想在函数2中嵌入我的函数func1,因为这会导致func1被定义多次(func2用于循环结构).

我已经尝试过简化代码以摆脱双循环,但由于问题的性质,这是不可能的.有任何想法吗?

Jos*_*ich 4

我想你想这样做sfExport(func1),尽管我不确定你是否需要在你的内部.GlobalEnv或内部进行func2。希望有帮助...

> y <- matrix(1:10,ncol=2)

> sfExport(list=list("func1"))

> func2(y)
     [,1] [,2]
[1,]    2    7
[2,]    3    8
[3,]    4    9
[4,]    5   10
[5,]    6   11
Run Code Online (Sandbox Code Playgroud)