2015-05-22 146 views
0

我嘗試編寫一個函數,在該函數中我可以拋出不定數量的對象並獲取該對象的數據類型列表。這是學習S3 Generics的一項個人任務。使用S3通用函數獲取數據類型列表

我迄今所做的是:

myTypes <- function(x, ...) { 
    dots <- list(...) 
    return (as.list(apply(dots, 1, myType))) 
} 

myType <- function(x){ 
    UseMethod("myType") 
} 

myType.numeric <- function(x){ 
    if(is.numeric(x)) "Type: numberic" 
} 

myType.data.frame <- function(x){ 
    if(is.data.frame(x)) "Type: dataframe" 
} 

如發生錯誤當我打電話

x <- 1 
y <- 3 

myTypes(x,y) 

我總是得到錯誤:"Error in apply(dots, 1, myType) : dim(X) must have a positive length",我不知道什麼是錯的。有人可以幫我嗎?由於我對R完全陌生,所以我可能會做一些基本錯誤的事情。

回答

1

apply的第一個參數必須是類矩陣對象(即矩陣,數組或數據框)。因爲你告訴apply沿第一維度應用函數和一個列表沒有尺寸

apply(1, 1, mean) 
#Error in apply(1, 1, mean) : dim(X) must have a positive length 

你傳遞一個列表apply,這不能工作:否則,你得到這個錯誤。

你可能想使用lapply而不是apply

myTypes <- function(...) { 
    dots <- list(...) 
    lapply(dots, myType) 
} 

x <- 1 
y <- 3 

myTypes(x,y) 
#[[1]] 
#[1] "Type: numberic" 
# 
#[[2]] 
#[1] "Type: numberic" 

當然,似乎更實用,簡單地返回類:

myTypes <- function(...) { 
    dots <- list(...) 
    lapply(dots, class) 
} 

myTypes(x,y) 
#[[1]] 
#[1] "numeric" 
# 
#[[2]] 
#[1] "numeric" 

順便說一句,如果您使用S3方法調度時,您不必在方法內部測試類,因爲如果對象具有相應的類,則只會調度方法。

+0

感謝您的幫助和良好的解釋!這幫助我很多! – ruedi