Generates a wrapper function that silences the output, messages, and/or warnings of a given function.

.silenceF(f, level = 7L)

Arguments

f

function to silence

level

a single numeric (integer) that indicates the silencing level, which encodes the set of output to be silenced.

It is interpreted like unix permission bit system, where each bit of the binary expression of the silencing level corresponds to a given type of output:

  • 0: nothing silenced;

  • 1: stdout;

  • 2: stderr messages;

  • 4: stderr warnings.

For example, level 3 = 2 + 1 means silencing stdout and stderr, while 5 = 3 + 2 means silencing stderr messages and warnings, but not outputs to stdout. The default value is 7 = 4 + 2 + 1, which silences all output.

Negative values are supported and mean "silence everything except the corresponding type", e.g., level = -1 silences all except stdout (computed as the binary complementary of 7, i.e. 7 - 1 = 5 = 3 + 2). See examples.

Value

a function

Examples

f <- function(){ cat("stdout message\n") message("stderr message") warning("stderr warning", immediate. = TRUE) } # example of generated wrapper g <- .silenceF(f) g
#> function (...) #> { #> utils::capture.output(suppressPackageStartupMessages(suppressMessages(suppressWarnings(res <- withVisible(f(...)))))) #> if (res$visible) #> res$value #> else invisible(res$value) #> } #> <environment: 0x5624226fd6a8>
# use of silencing level for(l in 7:-7){ message("\nLevel: ", l); .silenceF(f, l)() }
#> #> Level: 7
#> #> Level: 6
#> stdout message
#> #> Level: 5
#> stderr message
#> #> Level: 4
#> stdout message
#> stderr message
#> #> Level: 3
#> Warning: stderr warning
#> #> Level: 2
#> stdout message
#> Warning: stderr warning
#> #> Level: 1
#> stderr message
#> Warning: stderr warning
#> #> Level: 0
#> stdout message
#> stderr message
#> Warning: stderr warning
#> #> Level: -1
#> stdout message
#> #> Level: -2
#> stderr message
#> #> Level: -3
#> stdout message
#> stderr message
#> #> Level: -4
#> Warning: stderr warning
#> #> Level: -5
#> stdout message
#> Warning: stderr warning
#> #> Level: -6
#> stderr message
#> Warning: stderr warning
#> #> Level: -7
#> stdout message
#> stderr message
#> Warning: stderr warning
# inline functions ifun <- .silenceF(function(){ f(); invisible(1) }) ifun() ifun <- .silenceF(function(){ f(); 1 }) ifun()
#> [1] 1
ifun <- .silenceF(function(){ f(); 1 }, 2L) ifun()
#> stdout message
#> Warning: stderr warning
#> [1] 1