这是我的代码:
test <- function(y){
irisname <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width","Species")
if(y %in% irisname){
print(y)
} else{
test <- function(...) stop("dummy error")
test(y)
}
}
> test("ds")
Error in test(y) : dummy error
Run Code Online (Sandbox Code Playgroud)
在结果中:"Error in test(y) : dummy error "我在测试中需要"ds"("ds"),而不是测试(y).
我怎样才能做到这一点?
这几乎可以做到(有一个额外的冒号......),通过使用call.=FALSE来抑制有关调用的信息并将其入侵到错误消息中.
更新:为错误#1添加引号; 解释了为什么这个问题很难解释.
我不知道你的代码的结构,但你通过将对象更深入地传递到结构中来使自己的生活变得更加困难.stop()从第一级直接调用或y直接在错误消息中使用所携带的信息会容易得多.
test <- function(y,stop=FALSE){
irisname <- c("Sepal.Length","Sepal.Width",
"Petal.Length","Petal.Width","Species")
if (stop) stop(sprintf("premature stop: var %s",y))
if(y %in% irisname){
print(y)
} else{
test <- function(...) {
stop(sprintf("in test(\"%s\"): dummy error",...),
call.=FALSE)
}
test(y)
}
}
test("junk")
## Error: in test("junk"): dummy error
test("junk",stop=TRUE)
## Error in test("junk", stop = TRUE) : premature stop: var junk
Run Code Online (Sandbox Code Playgroud)
摆脱输出中的虚假第一个冒号test("junk")将会相当困难,因为Error:字符串在R中是硬编码的.最好的办法是,以某种方式打印自己的自定义错误消息,然后静默停止,或重新创建行为的stop(),而不会产生消息(参见?condition:例如return(invisible(simpleError("foo")))).但是,你将不得不跳过很多箍来做这件事,并且很难确保你获得完全相同的行为stop()(例如错误信息是否已保存在错误中) - 消息缓冲区?)
您想要做的事情可能就是通过充分利用R内部构件来实现,但在我看来,如此努力以至于重新考虑这个问题会更好......
祝好运.
您可以在函数开头检查参数。 match.arg可能会派上用场,或者您可以打印自定义消息并返回 NA。
下面有两个更新
> test <- function(y)
{
if(!(y %in% names(iris))){
message(sprintf('test("%s") is an error. "%s" not found in string', y, y))
return(NA) ## stop all executions and exit the function
}
return(y) ## ... continue
}
> test("Sepal.Length")
# [1] "Sepal.Length"
> test("ds")
# test("ds") is an error. "ds" not found in string
# [1] NA
Run Code Online (Sandbox Code Playgroud)
添加/编辑:当函数转到 时,您嵌套函数是否有原因else?我删除了它,现在得到以下内容。看起来你所做的只是检查一个参数,最终用户(和 RAM)希望立即知道他们是否输入了错误的默认参数。否则,您将调用不必要的工作并在不需要时使用内存。
test <- function(y){
irisname <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width","Species")
if(y %in% irisname){
print(y)
} else{
stop("dummy error")
}
}
> test("ds")
# Error in test("ds") : dummy error
> test("Sepal.Length")
# [1] "Sepal.Length"
Run Code Online (Sandbox Code Playgroud)
您也可以使用pmatch, 而不是match.arg, 因为match.arg会打印默认错误。
> test2 <- function(x)
{
y <- pmatch(x, names(iris))
if(is.na(y)) stop('dummy error')
names(iris)[y]
}
> test2("ds")
# Error in test2("ds") : dummy error
> test2("Sepal.Length")
# [1] "Sepal.Length"
Run Code Online (Sandbox Code Playgroud)