Skip to content

Instantly share code, notes, and snippets.

@anthonynorth
Last active March 8, 2024 08:08
Show Gist options
  • Save anthonynorth/f956b13e3574a17343a2b1915383cfea to your computer and use it in GitHub Desktop.
Save anthonynorth/f956b13e3574a17343a2b1915383cfea to your computer and use it in GitHub Desktop.
quietly
quietly <- function(fn) {
  # obvs not required in purrr namespace
  capture_output <- purrr:::capture_output

  rlang::new_function(
    rlang::fn_fmls(fn),
    rlang::expr(capture_output(!!rlang::fn_body(fn)))
  )
}

foo <- function(a, b, c = 3, ...) {
  c(a, b, c, ...)
}

z <- 6
quietly(foo)(1, 2, x = 4, y = 5, z = z)
#> $result
#>       x y z 
#> 1 2 3 4 5 6 
#> 
#> $output
#> [1] ""
#> 
#> $warnings
#> character(0)
#> 
#> $messages
#> character(0)

formals(quietly(foo))
#> $a
#> 
#> 
#> $b
#> 
#> 
#> $c
#> [1] 3
#> 
#> $...

plt <- function(y) plot(1:3, y)

png()
quietly(plt)(1:3)
#> $result
#> NULL
#> 
#> $output
#> [1] ""
#> 
#> $warnings
#> character(0)
#> 
#> $messages
#> character(0)
dev.off()
#> png 
#>   2

Created on 2024-03-08 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment