R debug()“无法找到函数”,即使它存在

时间:2019-09-06 09:18:12

标签: r function debugging scope

当我尝试调试某个功能(在功能NbCluster中自己定义)时,出现could not find function错误。我已经检查过,并且在调用debug时肯定加载了有问题的函数。

> data("USArrests")
> arrests <- scale(USArrests)
> source("NbCluster_copy.R")
> NbCluster_copy(data = arrests, diss = NULL, distance = "euclidean", min.nc = 2, max.nc = 12,
+                   method = "ward.D2", index = "gap", alphaBeale = 0.1)
[1] "Indice.Gap exists"
Error in debug(fun = "Indice.Gap") : could not find function "Indice.Gap"

如果我手动单步执行该功能(通过选择并运行行而不是调用该功能),则不会发生此问题。 我尝试制作一个最小的示例,但无法这样做,所以我认为问题不在于嵌套函数。

###This works as expected, when I run "wrapper", debug is called from within the function:
wrapper <- function(x){
wrapper <- function(x){
  fun1 <- function(x){
    fun0 <- function(x){
      y = x + 1
      return(y)
    }
    debug(fun0)
    y = fun0(x) * 2
    return(y)
  }
  fun1(x)
}

> wrapper(2)
debugging in: fun0(x)
debug at #3: {
    y = x + 1
    return(y)
}
Browse[2]> 
debug at #4: y = x + 1
Browse[2]> 
debug at #5: return(y)
Browse[2]> 
exiting from: fun0(x)
[1] 6

这是我添加到NbClust函数中的部分。

        if(exists("Indice.Gap")){
          print("Indice.Gap exists")
        }
        debug(fun = "Indice.Gap")

在第一次致电Indice.Gap之前:

        resultSGAP <- Indice.Gap(x = jeu, clall = clall, 
                                 reference.distribution = "unif", B = 10, method = "ward.D2", 
                                 d = NULL, centrotypes = "centroids")

除了上面显示的内容外,我仅做了非常小的更改,但是如果您要查看整个功能,我的副本在这里:https://pastebin.com/wxKKDbHy

1 个答案:

答案 0 :(得分:2)

只需在调试中删除引号,它就可以工作:

debug(Indice.Gap)

应该可以解决问题。

outer_fun <- function() {
   inner_fun <- function() 1
   ## does not work
   # debug("inner_fun") 

   ## works
   debug(inner_fun)
   inner_fun()
}

outer_fun()

您可以在顶层提供足够的功能名称作为字符串:

debug("outer_fun") # works
debug(outer_fun)   # works