Deliver a message after returning the result of the function

Consider the following function foo

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

I want to pass the message after the result of the function, so if the result is long, I do not need to scroll up to see if there was an important message (or change my max.print ). The problem is when I want to assign a result without printing the actual result.

Is there a way to print the result of a function followed by a message, but also so that nothing is printed when assigning the result? Ideally, I would like to avoid using print at all.

Desired outcome without assignment -

 > foo(5) # [1] 5 # test message 

The desired result with assignment is

 > bar <- suppressMessages(foo(5)) > bar # [1] 5 
+5
source share
1 answer

You can do this by creating a class for your foo function, for example. bar , and then create a print method for this new class.

For instance:

 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:

 foo(5) [1] 5 test message 

With purpose:

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

Some other ways to interact with the print method:

 print(x, message=FALSE) [1] 5 suppressMessages(print(x)) [1] 5 
+8
source

Source: https://habr.com/ru/post/1201125/


All Articles