首页 > 解决方案 > R调试()“找不到函数”,即使它存在

问题描述

当我尝试调试某个函数(它本身在函数 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

标签: rfunctiondebuggingscope

解决方案


只需删除调试中的引号,它应该可以工作:

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

推荐阅读