【问题标题】:Can't draw Histogram, 'x' must be numeric无法绘制直方图,“x”必须是数字
【发布时间】:2011-01-21 21:29:13
【问题描述】:

我有一个这种格式的数据文件:

Weight    Industry Type  
251,787   Kellogg  h  
253,9601  Kellogg  a  
256,0758  Kellogg  h  
....

我读取数据并尝试使用以下命令绘制直方图:

 ce <- read.table("file.txt", header = TRUE)

 we = ce[,1]
 in = ce[,2]
 ty = ce[,3]

hist(we)

但我收到此错误:

错误 en hist.default(we) : 'x' 必须是数字。

我需要做什么才能为我的三个变量绘制直方图?

【问题讨论】:

标签: r histogram


【解决方案1】:

由于千位分隔符,数据将被读取为“非数字”。所以你需要转换它:

 we <- gsub(",", "", we)   # remove comma
 we <- as.numeric(we)      # turn into numbers

现在你可以做

 hist(we)

和其他数字运算。

【讨论】:

  • 更正:不是千位分隔符,而是小数点,在某些国家/地区是逗号。所以需要用一个点来代替,而不是去掉。
  • 有一个参数 sep=""read.table, read.csv, ... 允许您在 R 级别进行设置。
【解决方案2】:

请注意,您也可以使用列名直接从ce(删除逗号后)绘制:

hist(ce$Weight)

(与使用 hist(ce[1]) 不同,这会导致相同的“必须是数字”错误。)

这也适用于数据库查询结果。

【讨论】:

  • 对我有帮助!数据类型已经是 dbl,但是我不能运行类似 hist(ce[,Weight]) 的东西。
【解决方案3】:

使用 dec 参数通过添加将"," 设置为小数点:

 ce <- read.table("file.txt", header = TRUE, dec = ",")

【讨论】:

  • 为什么这会让数据变成数字?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
相关资源
最近更新 更多