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?
They are all
FALSE
becauseapply()
coercesiris
to a matrix before it applies theis.numeric()
function. Fromhelp(apply)
regarding the first argument,X
-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 ofhelp(as.matrix)
.As Pascal has noted, you should use
sapply()
.Or the slightly more efficient
vapply()
.