获得data.frame的colclasses的优雅方式

时间:2011-11-14 22:55:54

标签: r dataframe

我目前使用以下函数列出data.frame的类:

sapply(names(iris),function(x) class(iris[,x]))

必须有一种更优雅的方式来做到这一点......

2 个答案:

答案 0 :(得分:9)

由于data.frames已经是列表,sapply(iris, class)只会起作用。 sapply将无法简化为扩展其他类的类的向量,因此您可以执行某些操作来获取第一个类,将类粘贴在一起等等。

答案 1 :(得分: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 ...

但要扩展@Jos​​huaUlrish优秀答案,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
相关问题