【问题标题】:When is a data.frame in R numeric?R数字中的data.frame何时是?
【发布时间】:2020-04-20 19:47:20
【问题描述】:

我偶然发现了以下问题。我有一个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

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

【问题讨论】:

  • 感谢您的回答,我意识到该示例并不真正等于我遇到的问题(现在已解决)。谢谢!
  • 抱歉,akrun,我不是故意的。还是谢谢你。

标签: r dataframe character numeric


【解决方案1】:

数据框始终是数据框,独立于其列的类。所以你得到的是预期的行为

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

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

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

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

【讨论】:

    【解决方案2】:

    我们需要在vector而不是data.frame上应用这个函数

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

    而不是

    is.numerc(A)
    

    根据?is.numeric

    只有当类的基类型是双精度或整数并且值可以合理地被视为数字时,is.numeric 的方法才应该返回 true(例如,对它们进行算术运算是有意义的,并且应该通过基类型进行比较) .

    “A”的classdata.frame 而不是numeric

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

    仅当对象的classnumericinteger 时,is.numeric 才会返回 TRUE。


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

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      相关资源
      最近更新 更多