gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:27:01 25 4
gpt4 key购买 nike

我有一个数据框。我要检查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和矩阵只能容纳一个“类”。如果有“字符”列,则结果将是单个“字符”类。要了解此检查
 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 ...

关于r - 在检查 data.frame 中的列类时 apply() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29187425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com