为什么apply()返回不正确的列类型? [英] Why does apply() return incorrect column types?

查看:106
本文介绍了为什么apply()返回不正确的列类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用R,而apply()函数使我绊倒了.非常感谢您的帮助:

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

但是

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

返回

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

发生了什么事?

推荐答案

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

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 -

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

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

因此,您已经拥有了它.实际上,所有列都在强制之后成为字符,因为矩阵只能采用一种数据类型(请参见as.matrix(iris)). help(as.matrix) Details 部分讨论了将整个内容强制转换为字符而不是其他某些数据类型的原因.

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

正如Pascal所指出的,您应该使用sapply().

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 

或更有效的vapply().

vapply(iris, is.numeric, NA)

这篇关于为什么apply()返回不正确的列类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆