“ Tibble”的行子集会丢失自定义s3类 [英] Row subsets of `Tibble` loses custom s3 class
本文介绍了“ Tibble”的行子集会丢失自定义s3类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我从数据框中提取一行,则我的自定义s3类保持不变:
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"
但这不适用于小标题:
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
推荐答案
答案来自Hadley 高级R书。您必须定义一个类构造函数和一个新的 [
函数。
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"
这篇关于“ Tibble”的行子集会丢失自定义s3类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文