Is there an easy way to print a dataframe to console in a delimited way?

Often you want to copy dataframes to spreadsheets, for example. In this case, the easiest thing to do is to readr::write_tsv and then copy the output file. I'm hoping for a way to instead capture the output string instead of the input, which write_tsv returns invisibly. This would let me pipe mtcars %>% FUN %>% writeLines(), for example.

There might be a packaged solution, but I usually fall back onto a textConnection for these tasks. They're connections like those created by file or unz, but the data is kept in a character vector.

The readr functions don't like text connections, but you can use the writing functions from utils.

captured_write <- function(..., sep = "\t") {
  con <- textConnection("out", "w")
  write.table(..., sep = sep,  file = con)
  close(con)
  out
}

mtcars %>%
  captured_write() %>%
  substr(start = 1, stop = 15) %>%
  head()
# [1] "\"mpg\"\t\"cyl\"\t\"di"
# [2] "\"Mazda RX4\"\t21 "
# [3] "\"Mazda RX4 Wag\""
# [4] "\"Datsun 710\"\t22"
# [5] "\"Hornet 4 Drive"
# [6] "\"Hornet Sportab"
1 Like

readr has a function format_tsv(df) that will print a data frame to the console.

mtcars %>% format_tsv()
[1] "mpg\tcyl\tdisp\thp\tdrat\twt\tqsec\tvs\tam\tgear\tcarb\n21\t6\t160\t110\t3.9\t2.62\t16.46\t0\t1\t4\t4\n21\t6\t160\t110\t3.9\t2.875\t17.02\t0\t1\t4\t4\n22.8\t4\t108\t93.................................."

It uses "\t" and "\n" as delimiters, so you may have to split it at "\n":
[You may use either base::strsplit("\\n") or string::str_split("\\n")]

mtcars %>% format_tsv() %>% strsplit("\\n")
[[1]]
[1] "mpg\tcyl\tdisp\thp\tdrat\twt\tqsec\tvs\tam\tgear\tcarb" "21\t6\t160\t110\t3.9\t2.62\t16.46\t0\t1\t4\t4"
[3] "21\t6\t160\t110\t3.9\t2.875\t17.02\t0\t1\t4\t4" "22.8\t4\t108\t93\t3.85\t2.32\t18.61\t1\t1\t4\t1"
..........

If you want the rownames printed as well, you'd have to add a function to make the row names another column, e.g., tibble::rownames_to_column()

mtcars %>% rownames_to_column() %>% format_tsv() %>% strsplit("\\n")
[[1]]
[1] "rowname\tmpg\tcyl\tdisp\thp\tdrat\twt\tqsec\tvs\tam\tgear\tcarb"
[2] "Mazda RX4\t21\t6\t160\t110\t3.9\t2.62\t16.46\t0\t1\t4\t4"
[3] "Mazda RX4 Wag\t21\t6\t160\t110\t3.9\t2.875\t17.02\t0\t1\t4\t4"

1 Like

Exactly what I was looking for! Can't believe I missed that.
This works perfectly to highlight and copy into a sheet:

mtcars %>% format_tsv %>% writeLines

Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.