为什么apply()返回不正确的列类型?

Kar*_*wal 4 r apply

所以我最近开始使用R并且该apply()功能正在绊倒我.我很感激这方面的帮助:

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
Run Code Online (Sandbox Code Playgroud)

但,

apply(iris, 2, FUN = is.numeric) 
Run Code Online (Sandbox Code Playgroud)

回报

Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
       FALSE        FALSE        FALSE        FALSE        FALSE 
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

Ric*_*ven 8

它们都是FALSE因为在应用函数之前apply()强制iris转换为矩阵is.numeric().从help(apply)第一个论点来看,X-

如果X不是数组而是具有非空暗淡值的类的对象(例如数据帧),则apply尝试通过as.matrix它是二维的(例如,数据帧)或通过将其强制转换为数组as.array.

is.array(iris)
# [1] FALSE
Run Code Online (Sandbox Code Playgroud)

所以你有它.实际上这些列在强制之后都变成了字符,因为矩阵只能采用一种数据类型(参见参考资料as.matrix(iris)).整个事物被强制转换为字符而不是其他数据类型的原因在详细信息部分讨论help(as.matrix).

正如Pascal所说,你应该使用sapply().

sapply(iris, is.numeric)
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#         TRUE         TRUE         TRUE         TRUE        FALSE 
Run Code Online (Sandbox Code Playgroud)

或者稍微高效一点vapply().

vapply(iris, is.numeric, NA)
Run Code Online (Sandbox Code Playgroud)