检查data.frame中的列类时,apply()不起作用 [英] apply() not working when checking column class in a data.frame
本文介绍了检查data.frame中的列类时,apply()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框.我想检查每一列的class
.
I have a dataframe. I want to inspect the class
of each column.
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()
来帮助我完成此操作.但这不起作用.
However, imagine that I have many columns and therefore need to use apply()
to help me do the trick. But it's not working.
apply(xdat, 2, class)
x1 x2
"character" "character"
为什么我不能使用apply()
来查看每一列的数据类型?或我该怎么办?
Why cannot I use apply()
to see the data type of each column? or What I should do?
谢谢!
推荐答案
您可以使用
sapply(xdat, class)
# x1 x2
# "integer" "factor"
使用apply
的
会将输出强制为matrix
,矩阵只能容纳一个类".如果有字符"列,则结果将是单个字符"类.要了解此支票
using apply
would coerce the output to matrix
and matrix can hold only a single 'class'. If there are 'character' columns, the result would be a single 'character' class. To understand this check
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 ...
这篇关于检查data.frame中的列类时,apply()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文