【问题标题】:'x' must be numeric error when trying to plot a histogram [duplicate]尝试绘制直方图时,“x”必须是数字错误[重复]
【发布时间】:2020-02-14 02:41:35
【问题描述】:

我正在尝试绘制直方图。但是,即使所有值似乎都是数字或 NA,当我尝试运行 hist() 时,它仍然返回错误。任何帮助将不胜感激。

corruption <- read.csv("Corruption.csv")
corruption[ corruption == "-" ] <- NA
hist(corruption$X2015)

我怀疑这与“-”字符的存在有关。当我使用 table(corruption$X2015) 时,这是输出:

 - 11 12 15 16 17 18 19 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 45 
 0  1  1  2  2  3  4  1  3  3  1  1  6  3  6  7  4  2  5  5  4  4  4  7  5  7  4  1  2  3  5  1 
46 47 49 50 51 52 53 54 55 56 58 60 61 62 63 65 70 71 74 75 76 77 79  8 81 83 85 86 87 88 89 90 
 2  2  1  1  4  2  3  1  4  3  1  1  3  2  2  1  4  1  1  3  2  1  2  2  3  1  1  1  2  1  1  1 
91 
 1 

【问题讨论】:

  • 您可能将此数据作为一个因素;这不会通过将“-”变为 NA 来改变

标签: r histogram


【解决方案1】:

X2015 转换为数字,这将自动将非数字更改为NA

corruption$X2015 <- as.numeric(as.character(corruption$X2015))

然后您可以使用hist

hist(corruption$X2015)

【讨论】:

  • 这很完美!你能解释一下为什么我需要使用 as.numeric AND as.character 而不是 as.numeric 吗?我尝试了后者,但没有成功。
  • @Wing.Wong273 因子在内部存储为数字。如果你直接使用as.numeric,你会得到底层数字。查看as.numeric(factor(c(12, 10)))as.numeric(as.character(factor(c(12, 10)))) 的输出
猜你喜欢
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 2019-01-08
  • 1970-01-01
相关资源
最近更新 更多