-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
仍然適合我。 –