在data.frame中检查列类时,apply()不起作用

时间:2015-03-21 20:03:08

标签: r class apply

我有一个数据框。我想检查每列的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()查看每列的数据类型?或者我应该做什么?

谢谢!

1 个答案:

答案 0 :(得分:7)

您可以使用

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

使用apply会将输出强制转换为matrix,矩阵只能容纳一个'类。如果有'字符'列,结果将是一个单一的字符'类。要理解这个检查

 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 ...