【问题标题】:Capture manually created messages from a function从函数中捕获手动创建的消息
【发布时间】:2021-06-29 19:22:36
【问题描述】:

我下面的函数foo() 产生3 种类型的消息。其中两个是message()创建的,一个是cat()创建的。

假设我通过lapply() 多次致电foo()

我想知道if() 我的lapply() 电话中是否有任何error message(包含术语错误的第二条消息)?

注意:我不想使用stopwarning

foo <- function(dat_obj) {
  
  v1 <- sapply(names(dat_obj), function(i) length(unique(dat_obj[[i]])))
  i1 <- names(which(v1 != 1))
  
  if(length(i1) == 1) {
    
    message(paste("Note: potential problem in",i1))
    
  } else if(length(i1) > 1) {
    
    message(paste("Error: fatal problem in x & y."))
    
  } else {
    
    cat(paste("OK: No issues detected.\n"))
  } 
}

#----- EXAMPLE OF USE:
INPUT <- list(
A = data.frame(x = c(1,1,1,1), y = c(2,4,3,3)),
B = data.frame(x = c(1,2,1,1), y = c(3,3,3,3)),
C = data.frame(x = c(1,2,1,1), y = c(3,2,3,3)),
D = data.frame(x = c(1,1,1,1), y = c(3,3,3,3)))


invisible(lapply(INPUT, foo))
#----- OUTPUT:
#Note: potential problem in y
#Note: potential problem in x
#Error: fatal problem in x & y.
#OK: No issues detected.

【问题讨论】:

  • messagecat 都返回不可见的 NULL。也许尝试不同的逻辑。
  • @RonakShah,我想知道if() 我们有任何来自我的lapply() 电话的error message(包含error 术语的第二条消息)?
  • @RuiBarradas,确定喜欢什么?
  • 就像我的回答,或者@RonakShah's。

标签: r list function dataframe error-handling


【解决方案1】:

您可以使用capture.output 来捕获函数返回的输出。

temp <- capture.output(lapply(INPUT, foo), type = 'message')
temp
#[1] "Note: potential problem in y"   "Note: potential problem in x"   
#    "Error: fatal problem in x & y."

要查找返回'Error' 的输出,您可以使用grep

grep('Error', temp)
#[1] 3

【讨论】:

    【解决方案2】:

    函数应该返回一些东西,即使只有invisible(NULL)。在下面的例子中,我将返回值更改为分配给变量yNA。那么逻辑测试数字 1、2 或 3 就是这个返回值的一个属性

    foo <- function(dat_obj) {
      v1 <- sapply(names(dat_obj), function(i) length(unique(dat_obj[[i]])))
      i1 <- names(which(v1 != 1))
      if(length(i1) == 1) {
        Attrib <- 1
        message(paste("Note: potential problem in",i1))
      } else if(length(i1) > 1) {
        Attrib <- 2
        message(paste("Error: fatal problem in x & y."))
      } else {
        Attrib <- 3
        cat(paste("OK: No issues detected.\n"))
      }
      y <- NA
      attr(y, "message") <- Attrib
      y
    }
    
    invisible(res <- lapply(INPUT, foo))
    sapply(res, attr, "message")
    

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      相关资源
      最近更新 更多