为什么 apply() 返回不正确的列类型? [英] Why does apply() return incorrect column types?
问题描述
我最近开始使用 R 并且 apply()
函数让我感到困惑.我很感激这方面的帮助:
I've recently started using R and the apply()
function is tripping me up. I'd appreciate help with this:
is.numeric(iris$Sepal.Length) # returns TRUE
is.numeric(iris$Sepal.Width) # returns TRUE
is.numeric(iris$Petal.Length) # returns TRUE
is.numeric(iris$Petal.Width) # returns TRUE
但是,
apply(iris, 2, FUN = is.numeric)
返回
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
FALSE FALSE FALSE FALSE FALSE
发生了什么事?
推荐答案
它们都是 FALSE
因为 apply()
将 iris
强制转换为在应用 is.numeric()
函数之前的矩阵.从 help(apply)
关于第一个参数,X
-
They are all FALSE
because apply()
coerces iris
to a matrix before it applies the is.numeric()
function. From help(apply)
regarding the first argument, X
-
如果 X
不是数组而是具有非 null 值的类的对象(例如数据框),则 apply
尝试将其强制转换为如果数组是二维的(例如,数据框),则通过 as.matrix
或通过 as.array
获取数组.
If
X
is not an array but an object of a class with a non-null dim value (such as a data frame),apply
attempts to coerce it to an array viaas.matrix
if it is two-dimensional (e.g., a data frame) or viaas.array
.
is.array(iris)
# [1] FALSE
所以你有它.由于矩阵只能采用一种数据类型(参见as.matrix(iris)
),列在强制转换后实际上都变成了字符.help(as.matrix)
的详细信息 部分讨论了整件事被强制转换为字符而不是其他数据类型的原因.
So there you have it. The columns actually all become character after the coercion because a matrix can only take on one data type (see as.matrix(iris)
). The reason the whole thing is coerced to character and not some other data type is discussed in the Details section of help(as.matrix)
.
正如 Pascal 所指出的,你应该使用 sapply()
.
As Pascal has noted, you should use sapply()
.
sapply(iris, is.numeric)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# TRUE TRUE TRUE TRUE FALSE
或者更高效的vapply()
.
vapply(iris, is.numeric, NA)
这篇关于为什么 apply() 返回不正确的列类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!