检查 data.frame 中的 class 列时 apply() 不起作用

apply() not working when checking column class in a data.frame

我有一个数据框。我想检查每列的 class

x1 = rep(1:4, times=5)
x2 = factor(rep(letters[1:4], times=5))
xdat = data.frame(x1, x2)

> class(xdat)
[1] "data.frame"
> class(xdat$x1)
[1] "integer"
> class(xdat$x2)
[1] "factor"

但是,假设我有很多列,因此需要使用 apply() 来帮助我实现这一目标。但是没用。

apply(xdat, 2, class)
         x1          x2 
"character" "character" 

为什么我不能使用 apply() 查看每一列的数据类型?或者我应该做什么?

谢谢!

你可以使用

sapply(xdat, class)
#     x1        x2 
# "integer"  "factor" 

使用 apply 会将输出强制为 matrix,矩阵只能容纳一个 'class'。如果有 'character' 列,结果将是单个 'character' class。看懂这个检查

 str(apply(xdat, 2, I))
 #chr [1:20, 1:2] "1" "2" "3" "4" "1" "2" "3" "4" "1" ...
 #- attr(*, "dimnames")=List of 2
 # ..$ : NULL
 # ..$ : chr [1:2] "x1" "x2"

现在,如果我们检查

 str(lapply(xdat, I))
 #List of 2
 #$ x1:Class 'AsIs'  int [1:20] 1 2 3 4 1 2 3 4 1 2 ...
 #$ x2: Factor w/ 4 levels "a","b","c","d": 1 2 3 4 1 2 3 4 1 2 ...