本文介绍了函数内使用sfApply时的范围界定问题(包装降雪 - R)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 让我在R中添加另一个范围问题,这次是用降雪包。如果我在全局环境中定义了一个函数,并且稍后我尝试在另一个函数内的sfApply()中使用该函数,那么我的第一个函数将不会再被找到: #Runnable代码。不要忘记用sfStop() require(snowfall) sfInit(parallel = TRUE,cpus = 3) func1 y< -x + 1 y } func2 y< - sfApply(x,2,函数(i)func1(i))y } y func2(y) sfStop() 这给出: > func2(y) checkForRemoteErrors(val)错误: 2个节点产生错误;第一个错误:找不到函数func1 如果我将函数嵌套到另一个函数中,有用。当我在全局环境中使用sfApply()时,它也可以工作。事情是,我不想在功能2中嵌套函数func1,因为这会导致func1被定义多次(func2用于类似循环的结构中)。 我试过已经简化了代码以摆脱双循环,但由于问题的性质,这是不可能的。任何想法?解决方案我想你想 sfExport(func1) ,但我不确定是否需要在 .GlobalEnv 中或 func2 中执行此操作。希望这有助于...... > y< - 矩阵(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 Let me add another scoping problem in R, this time with the snowfall package. 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 :#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. 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).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. 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 这篇关于函数内使用sfApply时的范围界定问题(包装降雪 - R)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-14 01:08