Consider the following function foo
foo <- function(x) {
print(x)
message("test message")
}
I'd like to deliver the message after the result of the function so that if the result is long I don't have to scroll up to see if there was an important message (or change my max.print
option). The issue is when I want to assign the result without printing the actual result.
Is there a way to print the result of the function, followed by the message, but also so that when I assign the result nothing at all is printed? Ideally, I'd like to avoid the use of print
altogether.
The desired result without assignment is
> foo(5)
# [1] 5
# test message
The desired result with assignment is
> bar <- suppressMessages(foo(5))
> bar
# [1] 5
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With