我目前使用下面的函数来列出data.frame的类的colclasses:优雅的方式来获得一个data.frame
sapply(names(iris),function(x) class(iris[,x]))
必须有一个更优雅的方式来做到这一点?
我目前使用下面的函数来列出data.frame的类的colclasses:优雅的方式来获得一个data.frame
sapply(names(iris),function(x) class(iris[,x]))
必须有一个更优雅的方式来做到这一点?
由于data.frames已经是列表,所以sapply(iris, class)
将会正常工作。 sapply
将不能简化为一个向量扩展其他类的类,所以你可以做一些事来采取第一类,这些类粘贴到一起,等
编辑如果你只是想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
什么'as.data.frame(sapply(光圈,类))'给出了一个很好的概述和参考应该很容易。 –