2012-04-06 18 views
2

對於某些軟件包,我可以看到特殊類型的對象。例如,當我嘗試從包中打印數據集時,我收到以下消息。在r中創建特殊數據對象

multitrait

This is an object of class "cross". 
    It is too complex to print, so we provide just this summary. 
    RI strains via selfing 

    No. individuals: 162 

......................and other summary information 

是(multitrait)

[1] "riself" 

我不知道我們如何能夠創造這樣的對象。它們是特殊的數據框列表,矢量矩陣。現在

X <- c("A", "B", "C") 
Y <- data.frame (A = 1:10, B = 21:30, C = 31:40) 
myeq <- c("Y ~ X1 + Y1") 
K <- 100 
A = 1:20 
B = B= 21:40 
J <- as.matrix(A,B) 
myl1 <- list(J, K) 

我複雜的對象:

mycomplexobject <- list(X, Y, myeq, K, J, myl1) 
mycomplexobject 
str(mycomplexobject) 

List of 6 
$ : chr [1:3] "A" "B" "C" 
$ :'data.frame':  10 obs. of 3 variables: 
    ..$ A: int [1:10] 1 2 3 4 5 6 7 8 9 10 
    ..$ B: int [1:10] 21 22 23 24 25 26 27 28 29 30 
    ..$ C: int [1:10] 31 32 33 34 35 36 37 38 39 40 
$ : chr "Y ~ X1 + Y1" 
$ : num 100 
$ : int [1:20, 1] 1 2 3 4 5 6 7 8 9 10 ... 
$ :List of 2 
    ..$ : int [1:20, 1] 1 2 3 4 5 6 7 8 9 10 ... 
    ..$ : num 100 

是(mycomplexobject)

[1] "list" "vector" 

有沒有辦法讓特殊對象和防止印刷整個列表像,而不是消息「打印很複雜「並提供總結呢?

+0

您可能會收到關於交叉驗證R經由更好的反應 - http://stats.stackexchange.com – arboc7 2012-04-06 02:01:42

+0

@ arboc7,這是一個關於R編程的問題,不是用R表示統計數據。它屬於SO。 – 2012-04-06 02:32:38

回答

6

只需設置對象的class並提供print方法。

class(mycomplexobject) <- c("too_complex", class(mycomplexobject)) 
print.too_complex <- function(x) { 
    cat("Complex object of length", length(x), "\n") 
} 
mycomplexobject 
+0

噢,很好......謝謝......當我發現這樣的對象時,我可以看到類似「 - attr(*,」class「)= chr [1:2]」riself「」cross「」,那可能是什麼意思?? – jon 2012-04-06 02:41:49

+1

'class'只是您可以附加到任何對象的屬性(即元數據) 。 某些方法,如'print'或'plot', 是通用的,即它們取決於它們的第一個參數的類型: 您可以檢查'methods(print)'或'methods(plot)'。 'class'屬性包含對象所屬的所有類 (這是多重繼承的實現方式): 在您的示例中,對象具有類'riself'(派生類) 和'cross'(父類) 。當你打印它時,R 將尋找以下方法: 'print.riself','print.cross','print.default' 並使用第一個存在。 – 2012-04-06 02:54:45