【发布时间】:2023-06-15 20:08:01
【问题描述】:
我正在尝试使用以下 glue 代码来创建信息丰富的错误消息
library(rlang)
library(glue)
my_function <- function(x) {
UseMethod("my_function", x)
}
my_function.default <- function(x) {
abort(glue(
"Can't calculate my_function because { deparse(substitute(x)) } is of type ",
glue_collapse(class(x))
))
}
使用这个测试列表,我们看到它有效:
test <- list(
x = c(1,2,3),
y = c("one", "two", "three")
)
my_function(test[[1]])
Error: Can't calculate my_function because test[[1]] is of type numeric
Run `rlang::last_error()` to see where the error occurred.
但是是否可以使用glue 来让错误返回x,它说test[[1]] 导致错误:
Can't calculate my_function because x is of type numeric
【问题讨论】:
-
我希望它返回列表元素的名称,所以如果我现在执行 my_function(test[[2]]) 它将返回“无法计算 my_function,因为 y 是字符类型”
-
你想要列表元素的名字
-
当您传入
test[[1]]时,您也不会传入名称。你可以编写代码来处理这个问题,但是你也可以为my_function(test$x)或my_function(fun_that_returns_list())或my_function(1:3)这样的情况编写特殊代码——在这些情况下会发生什么?如果您总是期望一个列表,那么您可能需要为列表本身和子集参数指定单独的参数。 -
如果在里面是不可能的。您可以传递两个参数,一个是列表和名称,这样会更容易
-
R 中任何类型的正常评估都不可能。值不知道它们在列表中的事实。只有列表知道它们的值的情况。