R 为什么apply()返回不正确的列类型?
我最近开始使用R,而R 为什么apply()返回不正确的列类型?,r,apply,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 但是, 返回 Sepal.Length Sepal.Width
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
但是,
返回
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
FALSE FALSE FALSE FALSE FALSE
发生了什么事?它们都是
FALSE
,因为apply()
在应用is.numeric()函数之前将iris
强制到矩阵。从关于第一个参数的help(apply)
中,X
-
如果X
不是数组,而是具有非空dim值(如数据帧)的类的对象,apply
尝试通过as.matrix
将其强制到数组(如果是二维(如数据帧)或通过as.array
)
好了。由于矩阵只能采用一种数据类型(请参见as.matrix(iris)
),因此强制后,列实际上都变成了字符。在帮助(as.matrix)
的详细信息部分讨论了将整个内容强制为字符而不是其他数据类型的原因
正如Pascal所指出的,您应该使用sapply()
或者更高效的vapply()
安装的功能是什么?请参见sapply(iris,is.numeric)
。此外,一些阅读:。
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
FALSE FALSE FALSE FALSE FALSE
is.array(iris)
# [1] FALSE
sapply(iris, is.numeric)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# TRUE TRUE TRUE TRUE FALSE
vapply(iris, is.numeric, NA)