R: How to suppress print output when the user assigns output of your function to a variable?

592 views Asked by At

Background

The t.test() function returns printed output as follows:

set.seed(2)
dat = rnorm(n = 50, mean = 0, sd = 1)
t.test(x = dat, mu = 0)

    One Sample t-test

data:  dat
t = 0.43276, df = 49, p-value = 0.6671
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 -0.2519143  0.3901901
sample estimates:
 mean of x 
0.06913791 

When the user assigns the output of this function to a variable the print output is suppressed:

a = t.test(x = dat, mu = 0)

I'm not sure how this is implemented. In my own function I have a message() that occurs prior to a return(). Toy example:

toy <- function(i){

  if(i > 0){

    message("i is greater than 0")

  }

  return(i)

}

Currently I give the user an option to set a silent parameter as TRUE or FALSE in order to suppress print output with an if() statement.

Question

Is there a way to suppress message/print output of a function automatically when the user assigns the function output to a variable?

0

There are 0 answers