在错误消息中获取变量? [英] Get variables in error messages?

查看:143
本文介绍了在错误消息中获取变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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 

在结果:测试错误(y):虚拟错误,我需要测试(ds)中的ds,而不是测试(y)。

In the result: "Error in test(y) : dummy error ", I need "ds" in test("ds"), not test(y).

我该怎么做?

推荐答案

在功能开始时的参数。 match.arg 可能会派上用场,或者您可以打印自定义消息并返回NA。

You could check the argument right at the start of the function. match.arg might come in handy, or you could print custom message and return 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

添加/编辑:当函数到 else 时,是否有一个为什么嵌套函数的原因?我删除它,现在得到以下内容。看来,您正在做的是检查参数,最终用户(和RAM)如果输入错误的默认参数,则立即知道它们。否则,您不需要调用不必要的工作并使用内存。

Add/Edit : Is there a reason why you're nesting a function when the function goes to else? I removed it, and now get the following. It seems all you are doing is checking an argument, and end-users (and RAM) want to know immediately if they enter an incorrect default arguments. Otherwise, you're calling up unnecessary jobs and using memory when you don't need to.

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"

您也可以使用 pmatch 而不是 match.arg ,因为 match.arg 打印出默认错误。

You could also use pmatch, rather than match.arg, since match.arg prints a default error.

> 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"

这篇关于在错误消息中获取变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆