【问题标题】:Why does R coerce numeric data to character when combined? [duplicate]为什么R在组合时将数字数据强制转换为字符? [复制]
【发布时间】:2019-06-09 15:36:24
【问题描述】:

在 R 中,我有一个由字符和数字字段组成的数据框。当我rbind data.frame 与另一个表时,整个data.frame 更改为character

发生了什么事?

x <-  data.frame("hello",1,2,3)

str(x)

x <- rbind(x,c("hello",1,2,3) )

str(x)

我希望在我的代码中找到一种不轻易更改数据类型的方法。

【问题讨论】:

  • 找不到完全相同的副本,但重点是 character 加上 numeric==character
  • also
  • 仔细阅读?c,您可能会受益匪浅。这解释了您遇到数据类型强制的原因。

标签: r types


【解决方案1】:

问题的根本原因似乎是您将rbind 与向量而不是数据框一起使用。 rbind() 旨在将两个数据帧按行连接在一起。作为这里的解决方案,请考虑使用带有数据框的rbind 作为第二个参数,例如

x <-  data.frame("hello",1,2,3)
class(x$X1)
x <- rbind(x, data.frame("hello",1,2,3))
class(x$X1)

[1] "numeric"
[1] "numeric"

【讨论】:

  • 另外,c("hello",1,2,3) 将所有内容更改为 "character" 类。
猜你喜欢
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多