gpt4 book ai didi

r - 获取错误使用的函数(来自调用)

转载 作者:行者123 更新时间:2023-12-02 16:07:47 24 4
gpt4 key购买 nike

我想从错误中提取正在使用的函数的名称。所以如果我有:

mean(letters)
"P" * 5

我想提取“mean.default”“*”。我可以从错误中获取调用,如下所示:

capturer <- function(x){
tryCatch({
x
}, warning = function(w) {
w
}, error = function(e) {
e
})
}

capturer(mean(letters))$call
## mean.default(letters)

capturer("P" * 5)$call
## "P" * 5

但是没有办法获取函数名称。

最佳答案

您可以使用$call[[1]]获取函数名称部分。我们还可以添加一个 deparse 参数来添加将结果作为字符串返回的选项。

capturer <- function(x, deparse = FALSE) {
out <- tryCatch({
x
}, warning = function(w) {
w$call[[1]]
}, error = function(e) {
e$call[[1]]
})
if(deparse) deparse(out) else out
}

## these return a call
capturer("P" * 5)
# `*`
capturer(mean(letters))
# mean.default

## these return a character
capturer("P" * 5, deparse = TRUE)
# [1] "*"
capturer(mean(letters), deparse = TRUE)
# [1] "mean.default"

关于r - 获取错误使用的函数(来自调用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33372530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com