【问题标题】:What arguments were passed to the functions in the traceback?哪些参数被传递给回溯中的函数?
【发布时间】:2013-05-11 01:01:10
【问题描述】:

在 R 中,如果由于错误而停止执行,我可以评估 traceback() 以查看错误发生在哪个函数中,该函数是从哪个函数调用的,等等。它会给出如下信息:

8: ar.yw.default(x, aic = aic, order.max = order.max, na.action = na.action, 
       series = series, ...)
7: ar.yw(x, aic = aic, order.max = order.max, na.action = na.action, 
       series = series, ...)
6: ar(x[, i], aic = TRUE)
5: spectrum0.ar(x)
4: effectiveSize(x)

有没有办法找到传递给这些函数的参数?在这种情况下,我想知道传递给effectiveSize() 的参数是什么,即x 是什么。

这个错误不是发生在我自己的代码中,而是在一个包函数中。作为 R 的新手,我有点迷茫。

不知道如何正确执行此操作,我试图找到包函数的定义并对其进行修改,但源文件应该在哪里我只找到了一个.rdb 文件。我假设这是字节编译的。

【问题讨论】:

    标签: r debugging


    【解决方案1】:

    我建议设置options(error=recover),然后再次运行有问题的代码。这一次,当遇到错误时,您将进入一个交互式调试环境,您可以在其中选择要调查的帧。它看起来很像traceback() 给你的,除了你可以输入7 进入调用堆栈上调用7 的评估环境。输入框架后,输入 ls() 将为您提供其参数列表。

    一个示例(基于 ?traceback 中的示例)可能是展示这一点的最佳方式:

    foo <- function(x) { print(1); bar(2) }
    bar <- function(x) { x + a.variable.which.does.not.exist }
    
    ## First with traceback()
    foo(2) # gives a strange error
    # [1] 1
    # Error in bar(2) : object 'a.variable.which.does.not.exist' not found
    traceback()
    # 2: bar(2) at #1
    # 1: foo(2)
    
    ## Then with options(error=recover)
    options(error=recover)
    foo(2) 
    # [1] 1
    # Error in bar(2) : object 'a.variable.which.does.not.exist' not found
    # 
    # Enter a frame number, or 0 to exit   
    # 
    # 1: foo(2)
    # 2: #1: bar(2)
    
    Selection: 1
    # Called from: top level 
    Browse[1]> ls()
    # [1] "x"
    Browse[1]> x
    # [1] 2
    Browse[1]>    ## Just press return here to go back to the numbered list of envts.
    # 
    # Enter a frame number, or 0 to exit   
    # 
    # 1: foo(2)
    # 2: #1: bar(2)
    

    R 有许多有用的调试工具,其中大部分在几年前的答案to this SO question 中进行了讨论。

    【讨论】:

      【解决方案2】:

      您可以使用trace() 将一个函数标记为需要“绕道”到另一个函数,逻辑选择是browser()。

       ?trace
       ?browser
      
      > trace(mean)
      > mean(1:4)
      trace: mean(1:4)
      [1] 2.5
      

      所以这只是显示调用。下一个迷你会话显示了实际上绕道进入浏览器的跟踪:

      > trace(mean, browser)
      Tracing function "mean" in package "base"
      [1] "mean"
      > mean(1:4)
      Tracing mean(1:4) on entry 
      Called from: eval(expr, envir, enclos)
      Browse[1]> x      #once in the browser you can see what values are there
      [1] 1 2 3 4
      Browse[1]> 
      [1] 2.5
      > untrace(mean)
      Untracing function "mean" in package "base"
      

      就函数中的内容而言,如果它被导出,您只需在控制台输入它的名称即可。如果未导出,则使用:getAnywhere(fn_name)

      【讨论】:

      • 您能否详细说明一下,或者举个例子?这对于初学者来说非常密集。
      猜你喜欢
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 2012-08-09
      • 1970-01-01
      • 2011-08-28
      相关资源
      最近更新 更多