2

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?

pomodoro
  • 297
  • 3
  • 12
  • similar to [this](https://r.789695.n4.nabble.com/How-to-stop-function-printing-unwanted-output-td897405.html) – Artur_Indio Oct 21 '19 at 02:43
  • The invisible() function will suppress printing in many cases where the output in not needed or wanted. – Gray Oct 21 '19 at 03:14
  • The reason `t.test`'s fancy output is displayed on the console in your first example is similar to why `1+1` displays `2` on the console, but `x = 1+1` does not. Assignment operations in general do *technically* return the assigned value as a result of the overall operation (which is why `a <- b <- 1` works), but it is returned (as @Gray said) *invisibly*, which means its `print` method (or `print.default`, if none) is not called on assignment but is otherwise. (You can prevent `invisible` by wrapping it in parens, so `(x = 1+1)` *will* print `2` on the console.) – r2evans Oct 21 '19 at 03:41

0 Answers0