R 中的 data.frame 什么时候是数字?

When is a data.frame in R numeric?

我偶然发现了以下问题。我有一个 data.frame

A <- data.frame(let = c("A", "B", "C"), x = 1:3, y = 4:6)

它的类列是

sapply(A, class)
      let         x         y 
 "factor" "integer" "integer" 
s.numeric(A$x)
[1] TRUE
is.numeric(A)
[1] FALSE

不明白为什么A$xB$x虽然是数值,但是仅由这两列组成的data.frame却不是数值

is.numeric(A[, c("x", "y")])
[1] FALSE

删除 factor 列没有帮助...

B <- A
B$let <- NULL
is.numeric(B)
[1] FALSE
is.numeric(B$x)
[1] TRUE
is.numeric(B$y)
[1] TRUE

因此,我尝试创建一个仅使用 A 中的数字列构建的新数据集。是数字吗?没有...

C <- data.frame(B$x, B$y)
is.numeric(C)
[1] FALSE
C <- data.frame(as.numeric(B$x), as.numeric(B$y))
is.numeric(C)
[1] FALSE

这里一定有我遗漏的东西。有帮助吗?

我们需要在 vector 而不是 data.frame

上应用函数
sapply(A[c("x", "y")], is.numeric)

而不是

is.numerc(A)

根据?is.numeric

Methods for is.numeric should only return true if the base type of the class is double or integer and values can reasonably be regarded as numeric (e.g., arithmetic on them makes sense, and comparison should be done via the base type).

'A'的classdata.frame而不是numeric

class(A)
#[1] "data.frame"

sapply(A, class)

is.numeric returns 仅当对象的 classnumericinteger.

时为真

因此,除非我们在 vector 或提取的列上应用 is.numeric,否则 data.frame 永远不会是 numeric。这就是原因,我们在 lapply/sapply 的循环中执行此操作,其中我们将列作为 vector 并且其 class 将是该列的 class

数据框始终是一个数据框,与其列的 类 无关。所以你得到的是预期的行为

如果要检查数据框中的所有列是否都是数字,可以使用以下代码

all(sapply(A, is.numeric))
## [1] FALSE
all(sapply(A[, c("x", "y")], is.numeric))
## [1] TRUE

一个只有数值数据的table也可以理解为矩阵。您可以将数据框的数字列转换为矩阵,如下所示:

M <- as.matrix(A[, c("x", "y")])
M
##      x y
## [1,] 1 4
## [2,] 2 5
## [3,] 3 6

矩阵 M 现在是真正的数字:

is.numeric(M)
## [1] TRUE