tbl_df被转换为S4类中的列表

时间:2018-08-13 15:11:33

标签: r s4 tibble

当我尝试在S4类中使用2.5时,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 对象一样访问tmp1@.Data吗?喜欢

tbl_df

2 个答案:

答案 0 :(得分:1)

为了简化起见,

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时,将获得小标题输出以及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

答案 1 :(得分:1)

contains = class(tibble())中使用setClass()。有关更多详细信息,请参见https://github.com/tidyverse/tibble/issues/618