Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 记录错误消息并将其写入数据帧_R_Error Handling_Try Catch - Fatal编程技术网

R 记录错误消息并将其写入数据帧

R 记录错误消息并将其写入数据帧,r,error-handling,try-catch,R,Error Handling,Try Catch,我打算在数据帧(比如ERR_LOG)中调用函数时记录R代码中的错误。我想在调用函数时使用“try”来识别错误(如果有)。数据帧(ERR_LOG)将包含以下列: 时间:调用函数的时间(Sys.Time) Loc:记录了哪个函数调用的此错误(函数名) 功能) 描述R向我们抛出的错误(错误消息 (右) 例如: 首先,我想用这些列初始化一个空白数据框“ERR_LOG” 然后编写函数 f <- function(a){ x <- a*100 return(x) } 在R中如何做到这一

我打算在数据帧(比如ERR_LOG)中调用函数时记录R代码中的错误。我想在调用函数时使用“try”来识别错误(如果有)。数据帧(ERR_LOG)将包含以下列:

  • 时间:调用函数的时间(Sys.Time)
  • Loc:记录了哪个函数调用的此错误(函数名) 功能)
  • 描述R向我们抛出的错误(错误消息 (右)
  • 例如:

    首先,我想用这些列初始化一个空白数据框“ERR_LOG”

    然后编写函数

    f <- function(a){
      x <- a*100
      return(x)
    }
    

    在R中如何做到这一点?

    使用
    tryCatch
    而不是
    try

    然后在
    tryCatch()中使用参数
    error=function(e){}

    e
    将有一个名为message的元素,这是您想要的

    使用以下浏览器调用浏览
    e$message

    x <- tryCatch(stop("This is your error message"), error=function(e) {browser()})
    

    x首先,调用
    f()
    时出现错误,因为您将其定义为接受参数
    a
    ,但调用时不传递任何值。@voidHead我知道这将导致三次错误。。但这只是一个例子来解释我想要记录的内容,你能解释一下如何创建所需的数据框并将数据插入其中吗?
    if(inherits(chk,'try-error'))
    
    {then I want to populate ERR_LOG and stop the code execution}
    
    x <- tryCatch(stop("This is your error message"), error=function(e) {browser()})
    
    MyErrorParser <- function(e) {
      m <- e$message
      if (grepl("something", m))
         do something
      return (something_else)
    }
    
    ## THEN
    tryCatch(stop("This is a test"), error=MyErrorParser)