Search code examples
rtibbler-s3vctrs

How can I apply custom-formatting to tibble list-columns using vctrs?


I am creating a new vctrs S3 class using new_list_of() but I can't find a way to control the printing of this class when used in tibbles. Here is a minimal example using a toy 'fruit_bowl' class. Ideally I'd like the columns to show the output of obj_print_data.fruit_bowl(), i.e. "2 types of fruit" and "1 type of fruit", but it seems the only thing that will print is the length of the vector.

library(vctrs)
library(tibble)
#> 
#> Attaching package: 'tibble'
#> The following object is masked from 'package:vctrs':
#> 
#>     data_frame

# Fruit bowl constructor function that uses `new_list_of`
fruit_bowl <- function(...) {
  x <- list(...)
  x <- lapply(x, vec_cast, character())
  new_list_of(x, ptype = character(), class = "fruit_bowl")
}

# Set the ptypes for nice printing
vec_ptype_full.fruit_bowl <- function(x, ...) "fruit_bowl"
vec_ptype_abbr.fruit_bowl <- function(x, ...) "frt_bwl"

# Formatting for fruit bowls
format.fruit_bowl <- function(x, ...) {

  format_fruits <- function(x) {
    n <- length(unique(x))
    sprintf("%d type%s of fruit", n, if (n == 1) "" else "s")
  }

  vapply(x, format_fruits, character(1))
}

# Printing for fruit bowls - use the 'format' function
obj_print_data.fruit_bowl <- function(x, ...) {
  if (length(x) == 0) {
    return()
  }
  print(format(x))
}

# Printing works nicely in isolation
fruit_bowl(c("banana", "apple"), "pear")
#> <fruit_bowl[2]>
#> [1] "2 types of fruit" "1 type of fruit"

# ...But not within tibbles
tibble(fruit_bowls = fruit_bowl(c("banana", "apple"), "pear"))
#> # A tibble: 2 x 1
#>   fruit_bowls
#>     <frt_bwl>
#> 1         [2]
#> 2         [1]

Created on 2021-04-10 by the reprex package (v0.3.0)


Solution

  • I jumped the gun and posted this question without fully reading the documentation. Here is the correct approach as outlined here

    pillar_shaft.fruit_bowl <- function(x, ...) {
      pillar::new_pillar_shaft_simple(format(x))
    }
    
    tibble(fruit_bowls = fruit_bowl(c("banana", "apple"), "pear"))
    #> # A tibble: 2 x 1
    #>   fruit_bowls     
    #>   <frt_bwl>       
    #> 1 2 types of fruit
    #> 2 1 type of fruit