apply() 在检查 data.frame 中的列类时不起作用 [英] apply() not working when checking column class in a data.frame

查看:19
本文介绍了apply() 在检查 data.frame 中的列类时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框.我想检查每一列的 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 ...

这篇关于apply() 在检查 data.frame 中的列类时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆