【问题标题】:Modifying the error message from a `stop()` call in R从 R 中的“stop()”调用中修改错误消息
【发布时间】:2020-10-16 05:53:11
【问题描述】:

在下面的stop 电话中,我收到一条消息,如下所示:

Error: cname not found in the 'data'.hhk not found in the 'data'.

我想知道是否有办法让消息看起来像:

'cname', 'hhk' not found in the 'data'.

这在 Base R 中可行吗?

vars = c("cname", "hhk")
a = 1
if(a) stop(paste(vars, "not found in the 'data'."))

Current Error message: Error: cname not found in the 'data'.hhk not found in the 'data'.
Desired Error message: 'cname', 'hhk' not found in the 'data'.

【问题讨论】:

    标签: r function dataframe


    【解决方案1】:

    vars 折叠成一个字符串:

    vars = c("cname", "hhk")
    a = 1
    if(a) stop(paste(toString(vars), "not found in the 'data'."))
    #Error: cname, hhk not found in the 'data'.
    

    【讨论】:

      【解决方案2】:

      您可以使用两个paste 命令来做到这一点:

      if(a) stop("'",paste(paste(vars,collapse = "', '",sep = ""), "' not found in the 'data'.",sep = ""))
      Error: 'cname', 'hhk' not found in the 'data'.
      

      【讨论】:

        【解决方案3】:

        我们可以使用stopifnot

        stopifnot(a)
        

        glue

        if(a) stop(glue::glue("{toString(vars)} not found in the data"))
        #Error: cname, hhk not found in the data
        

        【讨论】:

          猜你喜欢
          • 2022-01-22
          • 2023-03-15
          • 1970-01-01
          • 2020-03-25
          • 2013-10-07
          • 1970-01-01
          • 2019-06-17
          • 1970-01-01
          相关资源
          最近更新 更多