Suppress output of a function
Asked Answered
S

11

124

I'm looking to suppress the output of one command (in this case, the apply function).

Is it possible to do this without using sink()? I've found the described solution below, but would like to do this in one line if possible.

How to suppress output

Stagestruck answered 27/4, 2010 at 16:30 Comment(4)
Can you explain what you mean by 'do this inline'? Otherwise the question you cite already provides the answer and this is a duplicate.Dote
This solution requires three lines, one redirecting output, the command, and then another to turn output back on.Stagestruck
Or use capture.output. Or use *_ply from the plyr package.Watts
I second Hadley's suggestion- if you are really trying to execute an apply function, such as lapply, without printing output then 'l_ply` from his plyr package is probably the most appropriate choice.Nawab
K
117

It isn't clear why you want to do this without sink, but you can wrap any commands in the invisible() function and it will suppress the output. For instance:

1:10 # prints output
invisible(1:10) # hides it

Otherwise, you can always combine things into one line with a semicolon and parentheses:

{ sink("/dev/null"); ....; sink(); }
Koan answered 27/4, 2010 at 16:41 Comment(5)
Try 'invisible(cat("Hi\n"))' -- invisible() only suppresses the print of an expression, it is not a sink() one-liner.Dote
Right, but I think that it meets the needs of the questioner, unless I'm missing something in the question...Koan
For instance, this suppresses the return of apply, as per the question: invisible(apply(matrix(1:10), 1, as.numeric)).Koan
Rather than { sink("/dev/null"); ....; sink(); } I would definitely prefer capture.output, as capture.output effectively does exactly above, just a lot better (have a look at the source, it calls sink as in above fashion, plus some nice stuff around it).Bartlett
doesn't work on idw function under Windows. I think the best solution is using sinkYongyoni
N
73

Use the capture.output() function. It works very much like a one-off sink() and unlike invisible(), it can suppress more than just print messages. Set the file argument to "/dev/null" on UNIX or "NUL" on windows, or, better, use nullfile() (>= 3.6.0) for platform independence. If you need to support R< 3.6, use R.utils::nullfile(). For example, considering Dirk's note:

> invisible(cat("Hi\n"))
Hi

> capture.output(cat("Hi\n"), file = nullfile())
> 
Nawab answered 27/4, 2010 at 19:22 Comment(5)
doesn't work if you want to apply this to a function which returns some value and you want to use this valueYongyoni
@TMS Did something change during the last few month? I just tested to use the value returned by a function and it worked... capture.output(x <- log(2)) and afterwards x has the value of log(2)...Industrialist
This did not work for output in red.Jelsma
using nullfile() in your code is probably cleaner than platform-specific nullfile()/NUL ?Gravely
Works alright! Actually for a ggplot I also combined afterwards a suppressMessages to hide it completelyPrudenceprudent
L
31

The following function should do what you want exactly:

hush=function(code){
  sink("NUL") # use /dev/null in UNIX
  tmp = code
  sink()
  return(tmp)
}

For example with the function here:

foo=function(){
  print("BAR!")
  return(42)
}

running

x = hush(foo())

Will assign 42 to x but will not print "BAR!" to STDOUT

Note than in a UNIX OS you will need to replace "NUL" with "/dev/null"

Leoraleos answered 20/4, 2018 at 16:9 Comment(5)
This was the only answer that did what I needed, underrated.Freefloating
exactly what i needed tooDeroo
This did not work for me, still getting red letters outputJelsma
@SkyScraper - Can you please give a short toy example of what you're doing that causes this to fail?Leoraleos
@Leoraleos I figured out the issue, the output was messages() and this approach does not function for this kind of output. I had to use suppressMessages()Jelsma
H
11

R only automatically prints the output of unassigned expressions, so just assign the result of the apply to a variable, and it won't get printed.

Haematogenous answered 27/4, 2010 at 16:51 Comment(1)
Some functions have a print() or cat() in them that goes to the screen, not to an assignment.Dillard
A
11

you can use 'capture.output' like below. This allows you to use the data later:

log <- capture.output({
  test <- CensReg.SMN(cc=cc,x=x,y=y, nu=NULL, type="Normal")
})

test$betas
Abrade answered 16/12, 2014 at 6:9 Comment(1)
This did not work for output in red.Jelsma
R
7

In case anyone's arriving here looking for a solution applicable to RMarkdown, this will suppress all output:

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({

# Your code goes here
2 * 2
# etc
# etc


})})
```

The code will run, but the output will not be printed to the HTML document

Reportage answered 3/5, 2020 at 7:53 Comment(0)
S
0

Making Hadley's comment to an answer: Use of apply family without printing is possible with use of the plyr package

x <- 1:2
lapply(x, function(x) x + 1)
#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 3

plyr::l_ply(x, function(x) x + 1)
Sarsenet answered 27/4, 2010 at 16:30 Comment(0)
F
0
invisible(cat("Dataset: ", dataset, fill = TRUE))
invisible(cat(" Width: " ,width, fill = TRUE))
invisible(cat(" Bin1:  " ,bin1interval, fill = TRUE))
invisible(cat(" Bin2:  " ,bin2interval, fill = TRUE))
invisible(cat(" Bin3:  " ,bin3interval, fill = TRUE))

produces output without NULL at the end of the line or on the next line

Dataset:  17 19 26 29 31 32 34 45 47 51 52 59 60 62 63
Width:  15.33333

Bin1:   17 32.33333
Bin2:   32.33333 47.66667
Bin3:   47.66667 63
Fatigued answered 8/2, 2016 at 4:24 Comment(0)
H
0

Here is a version that is robust to errors in the code to be shushed:

quietly <- function(x) {
  sink("/dev/null") # on Windows (?) instead use `sink("NUL")`
  tryCatch(suppressMessages(x), finally = sink())
}
  • This is based directly on the accepted answer, for which thanks.
  • But it avoids leaving output silenced if an error occurs in the quieted code.
Hermineherminia answered 13/4, 2022 at 19:29 Comment(3)
OP asked for an answer which leaves out sink.Loose
OP accepted an answer which works via sink. This answer updates the accepted answer to avoid a pitfall arising if an error occurs in the code the answer is applied to.Hermineherminia
If your answer enhances an existing accepted answer its better practice to suggest an edit to that answer or suggest it as a comment below the answer. Regardless of what OP accepts, the answers provided should answer the question which is asked. Stack Overflow is a community. If someone else has the same question, wanting to avoid sink it will be marked as duplicate even though this question does not have an answer here.Loose
R
0

If you're wondering how to suppress a warning() you can use suppressWarnings() like so:

suppressWarnings(warning("hi"))

Whereas these two will still show the warning:

invisible(warning("Hi"))
# shows 'Hi'

capture.output(warning("Hi"), file='NUL')
# shows 'Hi'
Reportage answered 20/3, 2023 at 13:11 Comment(0)
O
0

for the return(something) part inside an R function:

return(invisible(something))  

works ok

invisible(return(something))

does not work at all

Otranto answered 9/6, 2023 at 9:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.