代码之家  ›  专栏  ›  技术社区  ›  Joris Meys

在函数中使用sfApply时的作用域问题(包snowfall-R)

  •  5
  • Joris Meys  · 技术社区  · 14 年前

    让我在R中添加另一个作用域问题,这次是snowfall包。如果我在全局环境中定义了一个函数,并且稍后在另一个函数中的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()
    

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

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

    2 回复  |  直到 14 年前
        1
  •  4
  •   Joris Meys    14 年前

    我想你想去 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
    
        2
  •  2
  •   Dirk is no longer here    14 年前

    另一种方法是使用foreach等,foreach(或迭代器?)中有一些例子文件显示了这一点。哦,看,乔希现在也推荐了同样的东西。