Row subsets of `Tibble` loses custom s3 class

我只是一个虾纸丫 提交于 2019-12-24 19:29:45

问题


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"


来源:https://stackoverflow.com/questions/54084280/row-subsets-of-tibble-loses-custom-s3-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!