r - 如何在R中获取函数调用的行号?

标签 r

出于调试目的,我想打印调用当前函数的位置的行号(和函数名称)。我如何在 R 中得到这个?

我看过 getting the source file name 的解决方案
但是如何获取行号和函数名?]

编辑:我找到了如何从 traceback() 获取这些数据以某种形式,回溯能够将其打印出来,但我不确定如何从中解码信息:

f <- function () {
    traceback(x = 3, max.lines = 1)
}

g <- function()
{
    f()
}

x <- g()

source("file.R") # file with this code
# 5: g() at file.R#20
# 4: eval(ei, envir)
# 3: eval(ei, envir)
# 2: withVisible(eval(ei, envir))
# 1: source("file.R")

str(x[[1]])
# chr "g()"
# - attr(*, "srcref")= 'srcref' int [1:8] 20 1 20 8 1 8 20 20
#  ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment:  0x0000000013a31700> 

最佳答案

找到了解决办法!从 traceback() 的代码中得到:

f <- function ()
{
    x <- .traceback(x = 1)

    srcloc <- if (!is.null(srcref <- attr(x[[1]], "srcref"))) {
        srcfile <- attr(srcref, "srcfile")
        paste0("Called from ", x[[2]], ", at ", basename(srcfile$filename), "#", srcref[1])
    }

    cat(srcloc, "\n")
}

g <- function()
{
    f()
}

g()
# Called from g(), at file.R#15

为它编写了一个很好的包装函数:
# returns a list, unless fmtstring is specified
# level: 1 - caller of the caller of this function; 2 - its parent, 3 - its grand-parent etc.
# fmtstring: return format string: %f (function), %s (source file), %l (line)
# 
# example: str <- caller_info("Called from %f at %s#%l\n")
# !!! it won't work with e.g. cat(caller_info("Called from %f at %s#%l\n"))
# or cat(paste0(caller_info("Called from %f at %s#%l\n"))) !!!
caller_info <- function (fmtstring = NULL, level = 1) # https://stackoverflow.com/q/59537482/684229
{
    x <- .traceback(x = level + 1)

    i <- 1
    repeat { # loop for subexpressions case; find the first one with source reference
        srcref <- getSrcref(x[[i]])
        if (is.null(srcref)) {
            if (i < length(x)) {
                i <- i + 1
                next;
            } else {
                warning("caller_info(): not found\n")
                return (NULL)
            }
        }
        srcloc <- list(fun = getSrcref(x[[i+1]]), file = getSrcFilename(x[[i]]), line = getSrcLocation(x[[i]]))
        break;
    }

    if (is.null(fmtstring))
        return (srcloc)

    fmtstring <- sub("%f", paste0(srcloc$fun, collapse = ""), fmtstring)
    fmtstring <- sub("%s", srcloc$file, fmtstring)
    fmtstring <- sub("%l", srcloc$line, fmtstring)
    fmtstring
}

这是它的使用方式:
f <- function ()
{
    str <- caller_info("Called from %f at %s#%l\n")
    cat(str)
}

唯一的(次要)限制是当在像 cat(caller_info("Called from %f at %s#%l\n")) 这样的子表达式中调用时或 cat(paste0(caller_info("Called from %f at %s#%l\n"))) , R 混淆地将这些子表达式的东西算作堆栈级别,这把它搞砸了。所以最好避免在表达式中使用这个包装器。

关于r - 如何在R中获取函数调用的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537482/

相关文章:

旋转箱线图图例(R,ggplot2)

python - 为什么在 2012 年 python 中的 pandas 合并比 R 中的 data.table 合并更快?

r - 在 R 中有效地将多个变量从字符重新编码为数值

r - 如果未提供变量,为什么用 data.table 插槽初始化 R S4 类不起作用

R/GIS : Find orthogonal distance between a location and nearest line

r - 用双标题在 R 中写入 .xlsx

javascript - 你能告诉 MutationObserver 只听特定的输入吗?在 pickerInput 中选择整组选项?

r - 如何在R中查找数据集

R - 如何找到最长的重复序列及其频率

r - 按 R 中的计数合并数据帧