我想创建一个 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.frame
tbl_df
,tbl
其中tbl_df
是用于打印的函数对象,并且tbl
是帮助中描述的通用方法。
那么如何将类定义RandomSample
为代表read_csv
输出对象的 S4 类呢?