【问题标题】:Row subsets of `Tibble` loses custom s3 class`Tibble` 的行子集丢失了自定义 s3 类
【发布时间】:2019-01-08 01:52:00
【问题描述】:

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

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"

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

【问题讨论】:

  • 我猜你可以为test_class 实现一个"[" 方法。
  • 有一些关于它的讨论herehere
  • 是的,谢谢你需要一个[ 方法和一个类构造函数。我现在正在回答我自己的问题
  • 也讨论here

标签: r dataframe tidyverse tibble


【解决方案1】:

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

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多