2011-11-14 38 views

回答

9

由於data.frames已經是列表,所以sapply(iris, class)將會正常工作。 sapply將不能簡化爲一個向量擴展其他類的類,所以你可以做一些事來採取第一類,這些類粘貼到一起,等

+1

什麼'as.data.frame(sapply(光圈,類))'給出了一個很好的概述和參考應該很容易。 –

3

編輯如果你只是想LOOK在類,可以考慮使用str

str(iris) # Show "summary" of data.frame or any other object 
#'data.frame':   150 obs. of  5 variables: 
# $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... 
# $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... 
# $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... 
# $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... 
# $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... 

但要擴大@JoshuaUlrish出色答卷,隨時間的data.frame或有序的因素列會引起疼痛與sapply解決方案:

d <- data.frame(ID=1, time=Sys.time(), factor=ordered(42)) 

# This doesn't return a character vector anymore 
sapply(d, class) 
#$ID 
#[1] "numeric" 
# 
#$time 
#[1] "POSIXct" "POSIXt" 
# 
#$factor 
#[1] "ordered" "factor" 

# Alternative 1: Get the first class 
sapply(d, function(x) class(x)[[1]]) 
#  ID  time factor 
#"numeric" "POSIXct" "ordered" 

# Alternative 2: Paste classes together 
sapply(d, function(x) paste(class(x), collapse='/')) 
#   ID    time   factor 
# "numeric" "POSIXct/POSIXt" "ordered/factor"  

請注意,這些解決方案都不是完美的。只獲得第一個(或最後一個)類可以返回一些毫無意義的東西。粘貼使得使用複合類更困難。有時候,你可能只是想檢測什麼時候出現這種情況,所以錯誤將是可取的(我愛vapply ;-)

# Alternative 3: Fail if there are multiple-class columns 
vapply(d, class, character(1)) 
#Error in vapply(d, class, character(1)) : values must be length 1, 
# but FUN(X[[2]]) result is length 2