Last active
November 12, 2022 15:01
-
-
Save bvancil/abe95e223a812ef3bf2107e73263ab68 to your computer and use it in GitHub Desktop.
copy or print a dataframe as tribble code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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