来自readr read_csv输出的S4类

时间:2017-01-03 16:50:03

标签: r s4 readr

我想创建一个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_dftbl其中tbl_df是一个函数对象用于打印,tbl是帮助中描述的通用方法。

那么如何将类RandomSample定义为表示read_csv输出对象的S4类?

1 个答案:

答案 0 :(得分:0)

通过安装最新版本的readr软件包(1.0.0)解决了该问题。 read_csv函数现在向对象添加了其他属性,这些属性在拉入S4类时有效。不完全明白为什么,但要慢慢学习。