Skip to content

Instantly share code, notes, and snippets.

@bvancil
Last active November 12, 2022 15:01
Show Gist options
  • Save bvancil/abe95e223a812ef3bf2107e73263ab68 to your computer and use it in GitHub Desktop.
Save bvancil/abe95e223a812ef3bf2107e73263ab68 to your computer and use it in GitHub Desktop.
copy or print a dataframe as tribble code
as_tribble_string <- function(df, delim = "|") {
headers <- df |>
names() |>
purrr::map(as.name) |>
paste0(a = "~", b = _, collapse = ", ")
# write contents to read back
output_file <- tempfile()
readr::write_delim(
df,
file = output_file,
delim = delim,
col_names = FALSE,
quote = "all"
)
inner_content <- output_file |>
readLines() |>
paste0(collapse = ",\n ") |>
gsub(delim, ", ", x = _, fixed = TRUE)
file.remove(output_file)
full_output <- paste0(
"tribble(\n",
" ", headers, ",\n",
" ", inner_content, "\n",
")\n"
)
full_output
}
print_as_tribble <- function(df) cat(as_tribble_string(df))
copy_as_tribble <- function(df) clipr::write_clip(as_tribble_string(df))
print_as_tribble(head(iris))
copy_as_tribble(head(iris))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment