Row subsets of `Tibble` loses custom s3 class

2019-08-19 16:02发布

问题:

If I extract a row from a dataframe, my custom s3 class stays:

test_df = iris

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

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

But this does not work for 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"

Is there a way around this? Thanks

回答1:

The answer comes from the s3 section of Hadley's Advanced R book. You have to define a class constructor function and a new [ function.

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"