This is useful if you simply want to copy-paste some code output without having to run code (or render/knit a whole document).
## 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
```
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