Why does apply() return incorrect column types?

左心房为你撑大大i 提交于 2019-12-31 00:59:52

问题


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

but,

apply(iris, 2, FUN = is.numeric) 

returns

Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
       FALSE        FALSE        FALSE        FALSE        FALSE 

What's going on?


回答1:


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 -

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 via as.matrix if it is two-dimensional (e.g., a data frame) or via as.array.

is.array(iris)
# [1] FALSE

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

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 

Or the slightly more efficient vapply().

vapply(iris, is.numeric, NA)


来源:https://stackoverflow.com/questions/34459064/why-does-apply-return-incorrect-column-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!