【问题标题】:tbl_df is transformed as list in S4 classtbl_df 被转换为 S4 类中的列表
【发布时间】:2019-01-20 08:50:33
【问题描述】:

当我尝试在 S4 类中使用 tbl_df 时,tbl_df 插槽似乎被转换为 list

library('tibble')
setOldClass(c('tbl_df', 'tbl', 'data.frame'))
setClass(Class = 'TestClass', slots = c(name = 'character'), contains = 'tbl_df')

tmp1 <- new('TestClass', tibble(x = 1:5, y = 1, z = x ^ 2 + y), name = 'firsttest')
tmp1@.Data
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 1 1 1 1 1

[[3]]
[1]  2  5 10 17 26

我可以像访问tbl_df 对象一样访问tmp1@.Data 吗?喜欢

tmp1@.Data
# A tibble: 5 x 3
      x     y     z
* <int> <dbl> <dbl>
1     1     1     2
2     2     1     5
3     3     1    10
4     4     1    17
5     5     1    26

【问题讨论】:

    标签: r s4 tibble


    【解决方案1】:

    setClass() 中使用contains = class(tibble())。更多详情见https://github.com/tidyverse/tibble/issues/618

    【讨论】:

      【解决方案2】:

      为简化起见,S3 对象是具有特殊属性“类”的列表,用于调用正确的通用函数。 print 是一个通用函数,在 R 输出 tibble 对象时被调用。

      library(tibble)
      tb <- tibble(x = 1:5, y = 1, z = x ^ 2 + y)
      
      dput(tb)
      #structure(list(x = 1:5, y = c(1, 1, 1, 1, 1), z = c(2, 5, 10, 
      #17, 26)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
      #"data.frame"))
      
      attributes(tb)
      #$`names`
      #[1] "x" "y" "z"
      #
      #$row.names
      #[1] 1 2 3 4 5
      #
      #$class
      #[1] "tbl_df"     "tbl"        "data.frame"
      

      当您使用 S3 父类创建 S4 类时,R 仅将列表存储在 .Data 插槽中。 R 仍然保留 S3 对象的属性,但不在 .Data 插槽中。当您打印TestClass 时,您将获得 tibble 输出以及 S4 插槽。如果只想要 S3 对象,您可以使用as(object,"S3")

      setOldClass(c('tbl_df', 'tbl', 'data.frame'))
      setClass(Class = 'TestClass', slots = c(name = 'character'), contains = 'tbl_df')
      tmp1 <- new('TestClass', tibble(x = 1:5, y = 1, z = x ^ 2 + y), name = 'firsttest1')
      tmp1
      #Object of class "TestClass"
      ## A tibble: 5 x 3
      #      x     y     z
      #* <int> <dbl> <dbl>
      #1     1     1     2
      #2     2     1     5
      #3     3     1    10
      #4     4     1    17
      #5     5     1    26
      #Slot "name":
      #[1] "firsttest1"
      
      attributes(tmp1)
      #$`names`
      #[1] "x" "y" "z"
      #
      #$row.names
      #[1] 1 2 3 4 5
      #
      #$.S3Class
      #[1] "tbl_df"     "tbl"        "data.frame"
      #
      #$name
      #[1] "firsttest1"
      #
      #$class
      #[1] "TestClass"
      #attr(,"package")
      #[1] ".GlobalEnv"
      
      as(tmp1,"S3")
      ## A tibble: 5 x 3
      #      x     y     z
      #* <int> <dbl> <dbl>
      #1     1     1     2
      #2     2     1     5
      #3     3     1    10
      #4     4     1    17
      #5     5     1    26
      

      【讨论】:

      • 感谢您的回答。这就是我想要的。
      猜你喜欢
      • 2016-06-09
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多