我有时会加载多个导出同名函数的包。例如,Hmisc 和 dplyr 都有 summarize
功能,我有时会同时加载两个包。然后我调用summarize
,以为我调用dplyr::summarize
当我真正调用 Hmisc::summarize
.发生这种情况时,我会收到如下错误消息:
Error in summarize(., mean = mean(instRating)) :
argument "by" is missing, with no default
该消息最初很难理解,因为我的代码不包含任何错误。我花了一分钟才意识到我在错误的包中调用了一个函数。如果它的第一行包含相关包的名称,则错误消息将更容易理解:
Error in Hmisc::summarize(., mean = mean(instRating)) :
有没有办法强制 R 在这些错误消息中显示包名?
我知道我可以通过输入
dplyr::summarize
来解决这个问题。或通过更改我加载包的顺序。但我的兴趣在于为 R 的错误消息添加细节。
最佳答案
来自基本选项的文档 error
:
'error': either a function or an expression governing the handling of non-catastrophic errors such as those generated by 'stop' as well as by signals and internally detected errors. If the option is a function, a call to that function, with no arguments, is generated as the expression. By default the option is not set: see 'stop' for the behaviour in that case. The functions 'dump.frames' and 'recover' provide alternatives that allow post-mortem debugging. Note that these need to specified as e.g. 'options(error = utils::recover)' in startup files such as '.Rprofile'.
因此,应该可以定义一个函数,该函数返回抛出错误的函数所在的包的名称。例如:
library(dplyr)
library(Hmisc)
data(mtcars)
print_package <- function() {
calls <- sys.calls()
call <- calls[[length(calls) - 1]]
fun.name <- as.character(call)[1]
pkg.name <- sub("package:", "", getAnywhere(fun.name)$where[1], fixed = TRUE)
message (paste0("In ", pkg.name))
}
options(error = print_package)
summarize(mtcars$mpg)
返回:
Error in summarize(mtcars$mpg) :
argument "by" is missing, with no default
In Hmisc
编辑(使用
rlang::trace_back
)事实证明,有一种更清洁的方法来做到这一点(归功于 Hadley Wickham 和他的“Advanced R, Second edition”):
library(dplyr)
library(Hmisc)
data(mtcars)
print_trace_back <- function() {
print(rlang::trace_back(bottom = sys.frame(-1)))
}
options(error = print_trace_back)
似乎可以优雅地处理错误:
> summarize(mtcars$mpg)
Error in summarize(mtcars$mpg) :
argument "by" is missing, with no default
█
1. └─Hmisc::summarize(mtcars$mpg)
>
> Hmisc::summarize(mtcars$mpg)
Error in Hmisc::summarize(mtcars$mpg) :
argument "by" is missing, with no default
█
1. └─Hmisc::summarize(mtcars$mpg)
>
> summarize(mtcars$mpg, as.character(mtcars$apa), mean)
Error in tapply(X, INDEX, FUN, ..., simplify = simplify) :
arguments must have same length
█
1. └─Hmisc::summarize(mtcars$mpg, as.character(mtcars$apa), mean)
2. └─Hmisc::mApply(X, byc, FUN, ..., keepmatrix = nc > 1)
3. └─base::tapply(X, INDEX, FUN, ..., simplify = simplify)
4. └─base::stop("arguments must have same length")
>
> (function() stop("Error"))()
Error in (function() stop("Error"))() : Error
█
1. └─(function() stop("Error"))()
2. └─base::stop("Error")
关于r - 强制 R 始终在错误消息中显示包名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62151751/