Skip to content

Instantly share code, notes, and snippets.

@tonyelhabr
Last active April 6, 2024 14:34
Show Gist options
  • Save tonyelhabr/265642a828ebee84a58bd96055d68c2f to your computer and use it in GitHub Desktop.
Save tonyelhabr/265642a828ebee84a58bd96055d68c2f to your computer and use it in GitHub Desktop.
Replicate reprex printing for arbitrary variables

This is useful if you simply want to copy-paste some code output without having to run code (or render/knit a whole document).

Method 1

## Based on internals of reprex:::reprex_impl
print_df_for_chunk <- function(code_string) {
  reprex_document_options <- list(
    venue = 'gh', 
    advertise = FALSE, ## non-default
    session_info = FALSE, 
    style = FALSE, 
    comment = '#>', 
    tidyverse_quiet = TRUE,
    std_out_err = FALSE
  )
  
  src <- c(
    reprex:::yamlify(reprex_document_options),
    code_string
  )
  r_file <- tempfile(fileext = '.R')
  on.exit(unlink(r_file))
  readr::write_lines(src, r_file)
  reprex_file <- reprex:::reprex_render_impl(
    r_file, 
    new_session = FALSE, ## non-default, look up in the global env
    html_preview = FALSE ## non-default
  )
  reprex:::expose_reprex_output(reprex_file) ## copy-paste
  invisible(readr::read_lines(reprex_file))
}

z <- tibble::tibble(
  x = c(1, 2),
  y = c('foo', 'bar')
)
print_df_for_chunk(z)
``` r
z
#> # A tibble: 2 × 2
#>       x y    
#>   <dbl> <chr>
#> 1     1 foo  
#> 2     2 bar
```

Method 2

This is even more succinct!

reprex_print <- function(...) {
  capture.output(...) |> 
    paste("#>", x = _) |> 
    cat(sep = "\n")
}
reprex_print(z)
#> # A tibble: 2 × 2
#>       x y    
#>   <dbl> <chr>
#> 1     1 foo  
#> 2     2 bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment