Deliver a message after returning the function result

后端 未结 1 411
眼角桃花
眼角桃花 2021-01-18 11:04

Consider the following function foo

foo <- function(x) {
    print(x)
    message(\"test message\")
}

I\'d like to deliver

相关标签:
1条回答
  • 2021-01-18 11:37

    You can achieve this by creating a class for your foo function, e.g. bar, and then creating a print method for this new class.

    For example:

    foo <- function(x) {
      class(x) <- c("bar", class(x))
      x
    }
    
    
    print.bar <- function(x, message=TRUE, ...){
      class(x) <- setdiff("bar", class(x))
      NextMethod(x)
      if(message)   message("test message")
    
    }
    

    Now try it:

    foo(5)
    [1] 5
    test message
    

    With assignment:

    x <- foo(5)
    x
    [1] 5
    test message
    

    Some other ways of interacting with the print method:

    print(x, message=FALSE)
    [1] 5
    
    suppressMessages(print(x))
    [1] 5
    
    0 讨论(0)
提交回复
热议问题