简体   繁体   English

在函数内使用sfApply时的作用域问题(程序包降雪-R)

[英]Scoping problem when sfApply is used within function (package snowfall - R)

Let me add another scoping problem in R, this time with the snowfall package. 让我在R中添加另一个范围问题,这次是降雪包。 If I define a function in my global environment, and I try to use that one later in an sfApply() inside another function, my first function isn't found any more : 如果我在全局环境中定义一个函数,并且稍后尝试在另一个函数内的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()

This gives : 这给出了:

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

If I nest my function inside the other function however, it works. 但是,如果我将函数嵌套在另一个函数中,则它将起作用。 It also works when I use the sfApply() in the global environment. 当我在全局环境中使用sfApply()时,它也可以工作。 Thing is, I don't want to nest my function func1 inside that function2, as that would cause that func1 is defined many times (func2 is used in a loop-like structure). 问题是,我不想将我的函数func1嵌套在那个function2内,因为那样会导致func1定义了很多次(func2在类似循环的结构中使用)。

I've tried already simplifying the code to get rid of the double looping, but that's quite impossible due to the nature of the problem. 我已经尝试简化代码以摆脱双重循环,但是由于问题的性质,这是完全不可能的。 Any ideas? 有任何想法吗?

I think you want to sfExport(func1) , though I'm not sure if you need to do it in your .GlobalEnv or inside of func2 . 我认为您想要sfExport(func1) ,尽管我不确定您是否需要在.GlobalEnvfunc2内部进行操作。 Hope that helps... 希望有帮助...

> 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

Methinks you are now confusing scoping with parallel computing. 有方法的人现在将范围界定与并行计算混为一谈。 You are invoking new R sessions---and it is commonly your responsibility to re-create your environment on the nodes. 您正在调用新的R会话-通常,您有责任在节点上重新创建环境。

An alternative would be to use foreach et al. 一种替代方法是使用foreach等。 There has examples in the foreach (or iterator ?) docs that show exactly this. 在foreach(或iterator吗?)文档中有一些示例准确地显示了这一点。 Oh, see, and Josh has by now recommended the same thing. 哦,明白了,乔希(Josh)到目前为止推荐了同样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM