-1
我想创造它代表从read_csv
函数调用(readr
包)中的数据S4类
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
我尝试以下基本类设置一个S4类
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类?
虽然您的示例不是严格重复性的,但我不知道您的数据是什么样的,所以我没有使用您的代码出现错误。顺便说一句,setClass中的表示形式的使用已被弃用。 –
@David_B:道歉,我稍后意识到我忘了添加可重现的数据变量。我现在编辑了这个问题。然而,从'representation'改为'slots'并不会改变结果。 – andrnev
仍然适合我。 –