[英]How can I apply custom-formatting to tibble list-columns using vctrs?
我正在使用new_list_of()
創建一個新的vctrs
S3 class 但我無法找到一種方法來控制這個 class 在用於小標題時的打印。 這是一個使用玩具“ fruit_bowl
”class 的最小示例。 理想情況下,我希望列顯示obj_print_data.fruit_bowl()
的 output ,即"2 types of fruit"
和"1 type of fruit"
,但似乎唯一會打印的是向量的長度。
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]
由代表 package (v0.3.0) 於 2021 年 4 月 10 日創建
我沒有完全閱讀文檔就開槍發布了這個問題。 這是此處概述的正確方法
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.