我想创建一个以某种方式打印
tibble
对象的类,本质上是在调用时打印包中存储的所有数据集。我对如何使其发挥作用感到非常困惑。
这是我目前的状态,尝试了以下各种变化但没有成功。
理想情况下,这会像正常的
zz
一样打印 tbl_df
,但具有指定的行数(在本例中为 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"
创建于 2024-04-12,使用 reprex v2.0.2
想法/祈祷? 🙏🏼
我不熟悉
setClass()
,但我认为你可以使用S3方法调度来做你想做的事:
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
以防万一您错过了,
print()
对于 tibble
有用于显示行数和列数的附加选项(除其他外):https://tibble.tidyverse.org/reference/formatting.html