【问题标题】:maybe 'breaks' do not span range of也许“休息”不跨越
【发布时间】:2016-10-11 01:54:45
【问题描述】:

有没有人知道如何解决以下错误消息:一些'x'未计算在内;也许'breaks'不跨越'x'的范围

> mydata = read.csv("Income.csv")
> attach(mydata)
> X = Income[!is.na(Income)]#exclude NA value in mydata
> B = seq(floor(min(X)),ceiling(max(X)),by=10)
> hist(X,break=B)
Error in hist.default(X, breaks = B) : 
  some 'x' not counted; maybe 'breaks' do not span range of 'x'
>str(X)
 num [1:747] 53.92 25.32 0.98 13.12 54.88 ...

我已经将 seq() 从 min(X) 设置为 max(X) 为什么仍然有错误? 顺便说一句,当我设置为 = 0.1 时它可以工作,但这不是我想要的 帮我!!

【问题讨论】:

  • seq(x1, x2, by = dx) 不一定 必须跨越整个范围 [x1, x2]。参见例如 seq(1, 10, by = 4),它给出 (1,5,9)。您可以使用seq(x1, x2, length.out = n) 确保序列跨越整个范围。
  • 这背后的原因是by = x允许你指定步宽,而length.out = n允许你指定步数。详情请见?seq
  • 顺便说一句,我注意到你使用attach()。可能是你应该改掉的习惯。它可能会导致意外名称冲突等问题,而且从来没有必要。还有更好的替代方案 - 查看with,并注意具有data= 参数的函数。像 data.table 和 dplyr 这样的包也可以让你以简写的方式引用列名,而不需要附加。
  • 我用seq(x1, x2, length.out = n) 查了一下,怎么知道这个序列跨越了全范围?
  • 什么意思? breaks <- seq(x1, x2, length.out = n); print(breaks)?此外,您的错误消息应该会消失。

标签: r


【解决方案1】:

在直方图中指定中断的不同方法。

# Generate some data
# Note: I use "ugly" numbers to demonstrate the use of ceiling/floor
set.seed(100);
X <- runif(10000, min = 18720.8, max = 199420.2);

# This will throw an error:
# Error in hist.default(X, breaks = breaks) :
#  some 'x' not counted; maybe 'breaks' do not span range of 'x'
breaks <- seq(floor(min(X)), ceiling(max(X)), by = 10000);
hist(X, breaks = breaks);

# Either specify the number of breaks directly
hist(X, breaks = 100);

# or specify the number of breaks in your sequence of breaks
breaks <- seq(floor(min(X)), ceiling(max(X)), length.out = 100);
hist(X, breaks = breaks);

# or specify the step width in your sequence of breaks.
# Note: Here you have to make sure that you span the full range of X
breaks <- seq(floor(min(X)), 
              ceiling(max(X)) + ifelse(ceiling(max(X)) %% 10000 != 0, 10000, 0), 
              by = 10000);
hist(X, breaks = breaks);

您可以从最后一个示例中看到,固定 bin 宽度如何导致最后一个 bin 不“满”,因为它“扩展”了 X 的最大值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2018-06-19
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    相关资源
    最近更新 更多