Home > other >  How can I make a function that prints something only if it's called directly?
How can I make a function that prints something only if it's called directly?

Time:10-08

I would like to create a function (similar to ggplot or lm) that prints a value - other than what's being returned - only if it's not called by other functions (except print).

What I've tried:

my_fun <- function(x){
  print(0)
  invisible(x   1)
}
my_fun(1)         #> 0    works as desired
print(my_fun(1))  #> 0 2  should print only 0 
val <- my_fun(1)  #> 0    shouldn't print anything

CodePudding user response:

There's probably multiple ways to achieve this, but essentially you need to define a custom print method for the output of my_fun. In gglot2 the function returns a data structure but the print method for that data structure is what actually renders it visually.

Here's an example of using an S3 class

my_fun <- function(x){
  invisible(structure(x   1, class = "myClass"))
}

print.myClass <- function(x, ...) {
  print(0)
}

my_fun(1)         
print(my_fun(1)) 
#> [1] 0
val <- my_fun(1) 
  • Related