`Tibble` 的行子集丢失自定义 s3 class

Row subsets of `Tibble` loses custom s3 class

如果我从数据框中提取一行,我的自定义 s3 class 保持:

test_df = iris

class(test_df) <- c("test_class", class(test_df))

class(test_df[1,])
[1] "test_class" "data.frame"

但这不适用于 tibbles:

test_df <- as_tibble(test_df)
class(test_df) <- c("test_class", class(test_df))
class(test_df[1,])
[1] "tbl_df"     "tbl"        "data.frame"

有办法解决这个问题吗? 谢谢

答案来自 Hadley 的 Advanced R book 的 s3 部分。您必须定义一个 class 构造函数和一个新的 [ 函数。

new_test <- function(x, ...) {

  structure(x, class = c("test_class", class(x)))
}

`[.test_class` <- function(x, ...) {
  new_test(NextMethod())
}

test_df <- iris
test_df <- as_tibble(test_df)
class(test_df) <- c("test_class", class(test_df))
class(test_df[1,])
[1] "tbl_df"     "tbl"        "data.frame"