Original question
I am developing an R data package that provides a bunch of data table objects.
When the user of my package asks for one of these data tables to be printed to the console, I would like them to be pretty printed just like tibbles are, i.e. nicely condensed, with column type at the top and some basic coloring of numbers, etc..
So would you know how to write a simple S3 method for data tables in my package? Perhaps this already exists implemented elsewhere but I could not find it.
I know there is this other question that is similar to this one: Print pretty data.frames/tables to console, and that this has been partly answered by @csgillespie but he only leaves the suggestion that one could write an S3 method for data.frames. But given that I want to borrow the functionality already developed for tibbles (tbl_df), isn't there a simple mechanism of importing this either from the {tibble} package, or the {pillar} package where seemingly this functionality is nowadays originally implemented?
BTW: I do not want to simply convert the data table object to a tibble with e.g. tibble::as_tibble() because then I lose the advantages of having data table objects.
Specific pretty printing of exported data tables
After @Waldi's answer, I thought of an alternative way that would only pretty print the data tables provided my package and not all of the data tables once my package is loaded. Here's my approach for which I would like your feedback.
- Add the made-up class
dt_tblto the data table, in other words, subclass it:
# Assume `dt` is one of the data tables provided by my package
class(dt) <- c('dt_tbl', class(dt))
- Then in the R directory of my package, create a source file with the new S3 method for the class
"dt_tbl":
# In file print_dt_tbl.R
#' @keywords internal
print_dt_tbl <- function(x, ...) {
print_txt <- capture.output(print(tibble::as_tibble(x), ...))
print_txt[1] <- sub('tibble', 'data.table', print_txt[1])
cat(print_txt, sep = '\n')
invisible(x)
}
#' @export
print.dt_tbl <- function(x, ...) {
print_dt_tbl(x, ...)
}
- Test it:
> (iris_dt <- data.table::as.data.table(iris))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1: 5.1 3.5 1.4 0.2 setosa
2: 4.9 3.0 1.4 0.2 setosa
3: 4.7 3.2 1.3 0.2 setosa
4: 4.6 3.1 1.5 0.2 setosa
5: 5.0 3.6 1.4 0.2 setosa
---
146: 6.7 3.0 5.2 2.3 virginica
147: 6.3 2.5 5.0 1.9 virginica
148: 6.5 3.0 5.2 2.0 virginica
149: 6.2 3.4 5.4 2.3 virginica
150: 5.9 3.0 5.1 1.8 virginica
> class(iris_dt) <- c('dt_tbl', class(iris_dt))
> iris_dt
# A data.table: 150 x 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5 3.4 1.5 0.2 setosa
9 4.4 2.9 1.4 0.2 setosa
10 4.9 3.1 1.5 0.1 setosa
# … with 140 more rows