【发布时间】:2017-01-03 16:50:02
【问题描述】:
我想创建一个 S4 类,它代表来自read_csv 函数调用(readr 包)的数据
library(readr)
library(magrittr)
#data <- read_csv("random.csv")
data <- structure(list(id = c(10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 30L,
30L, 30L, 30L, 30L, 30L, 30L, 30L, 30L, 30L),
value = c(0.711074015,
0.614819585, 0.791768651, 0.385054413, 0.658395941, 0.204337366,
0.800191712, 0.049692407, 0.106693474, 0.989649574, 0.622873403,
0.269687142, 0.705086413, 0.520805849, 0.951492967, 0.63948476,
0.691096167, 0.284000329, 0.873882314, 0.48240776, 0.156761559,
0.149020867, 0.054223854, 0.429401826, 0.973400059, 0.030492575,
0.084345713, 0.538730795, 0.100815694, 0.443863626)),
class = c("tbl_df","tbl", "data.frame"),
row.names = c(NA, -30L), .Names = c("id","value"))
> head(data)
Source: local data frame [6 x 2]
id value
(int) (dbl)
1 10 0.7110740
2 10 0.6148196
3 10 0.7917687
4 10 0.3850544
5 10 0.6583959
6 10 0.2043374
我尝试了以下基本类设置
setClass(
Class="RandomSample",
slots=c(data="data.frame"),
contains=c("data.frame")
)
createContainer <- function(myData)
{
return(new(Class = "RandomSample",data = myData))
}
containerBase <- createContainer(data)
这会引发错误
Error in validObject(.Object) :
invalid class “RandomSample” object: 1: invalid object for slot "data" in class "RandomSample": got class "tbl_df", should be or extend class "data.frame"
invalid class “RandomSample” object: 2: invalid object for slot "data" in class "RandomSample": got class "tbl", should be or extend class "data.frame"
invalid class “RandomSample” object: 3: invalid object for slot "data" in class "RandomSample": got class "data.frame", should be or extend class "data.frame"
我意识到read_csv创建的对象不是S4类,它有三个对象data.frametbl_df和tbl,其中tbl_df是用于打印的函数对象,tbl是通用方法如帮助中所述。
那么如何将RandomSample 类定义为代表read_csv 输出对象的S4 类?
【问题讨论】:
-
我在使用您的代码时没有收到错误,尽管您的示例不是严格可重现的,因为我不知道您的数据是什么样的。顺便说一句,不推荐在 setClass 中使用表示形式。
-
@David_B:抱歉,我后来意识到我忘了添加可重现的数据变量。我现在已经编辑了这个问题。从
representation更改为slots不会改变结果。 -
对我来说仍然可以正常工作。
-
@David_B:这很奇怪。如果您执行
class(containerBase),您会得到类的名称为 RandomSample 吗? -
是的,我愿意。
class(containerBase) [1] "RandomSample" attr(,"package") [1] ".GlobalEnv