rpackager-s3

Create print method for class based on existing class (i.e., print `tibbles` longer)


I want to create a class that prints tibble objects in a certain way, essentially to print all of some data sets stored in a package when called. I am getting pretty lost as to how to make that work.

Here's my current state, having tried variations on the below to no success.

Ideally, this would print zz like a normal tbl_df but with the specified number of rows (in this example n = 3)

library(tibble)

long_tibble <- setClass(
  Class = "long_tibble",
  slots = c(tab = "tbl_df"),
  contains = "tbl_df"
)

print.long_tibble <- function(x){
  x@tab |>
    tibble::as_tibble() |>
    print(n = 3)
}

zz <- tibble::tibble(a = 1:10)
class(zz) <- "long_tibble"
zz
#> Error in x@tab: no applicable method for `@` applied to an object of class "long_tibble"

xx <- long_tibble(tab = zz)
#> Error in as(slotVal, slotClass, strict = FALSE): no method or default for coercing "long_tibble" to "tbl_df"
zz
#> Error in x@tab: no applicable method for `@` applied to an object of class "long_tibble"

Created on 2024-04-12 with reprex v2.0.2

Thoughts / prayers? 🙏🏼


Solution

  • I'm not familiar with setClass() but I think you could use the S3 method dispatch to do what you want:

    library(tibble)
    
    print.long_tibble <- function(x){
      x |>
        tibble::as_tibble() |>
        print(n = 3)
    }
    
    zz <- tibble::tibble(a = 1:10)
    class(zz) <- c("long_tibble", class(zz))
    zz
    #> # A tibble: 10 × 1
    #>       a
    #>   <int>
    #> 1     1
    #> 2     2
    #> 3     3
    #> # ℹ 7 more rows
    

    Just in case you missed it, print() for tibble has additional options for the number of rows and of columns to display (among other things): https://tibble.tidyverse.org/reference/formatting.html