【发布时间】:2025-12-30 15:30:11
【问题描述】:
我目前使用以下函数来列出 data.frame 的类:
sapply(names(iris),function(x) class(iris[,x]))
必须有更优雅的方式来做到这一点......
【问题讨论】:
我目前使用以下函数来列出 data.frame 的类:
sapply(names(iris),function(x) class(iris[,x]))
必须有更优雅的方式来做到这一点......
【问题讨论】:
由于 data.frames 已经是列表,sapply(iris, class) 可以正常工作。 sapply 将无法简化为扩展其他类的类的向量,因此您可以采取一些措施来获取第一类,将类粘贴在一起等。
【讨论】:
as.data.frame(sapply(iris,class)) 怎么样?提供了一个很好的概述,参考应该很容易。
编辑如果您只想看看课程,请考虑使用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
【讨论】: