Why does apply() return incorrect column types?

我是研究僧i 提交于 2019-12-01 19:00:26

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