如何获取数据框中所有列的类?


Answers:


91

一种选择是使用lapplyclass。例如:

> foo <- data.frame(c("a", "b"), c(1, 2))
> names(foo) <- c("SomeFactor", "SomeNumeric")
> lapply(foo, class)
$SomeFactor
[1] "factor"

$SomeNumeric
[1] "numeric"

另一种选择是str

> str(foo)
'data.frame':   2 obs. of  2 variables:
 $ SomeFactor : Factor w/ 2 levels "a","b": 1 2
 $ SomeNumeric: num  1 2

20
另外sapply(foo, class)
MYaseen208

9
由于class返回对象继承的所有类的字符向量,因此输出的sapply(foo, class)可能是列表,而不是大多数人期望的那样总是字符向量。这可能有点危险...我发现lapply安全得多。
flodel

1
为了获得更好的可读性,我建议:unlist(lapply(foo, class))这对于带有很多列的数据帧很方便。
p130ter

1
unlistwithlapply是一个可怕的主意,因为length(class(x))>1 (参见上面的评论)-可能sapply比更加安全unlist + lapply。一个安全的办法是sapply(lapply(foo, class), "[", 1)-因为foo是一个数据帧
lebatsnok

27

您可以简单地使用lapplysapply内置函数。

lapply会给你一个list-

lapply(dataframe,class)

sapply将采用最佳返回类型ex。矢量等-

sapply(dataframe,class)

这两个命令都将为您返回所有列名称及其各自的类。



0

您也可以使用purrr,这类似于apply家庭功能:

as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.