【问题标题】:How to assign a different bin size to the head and tails of a distribution in hist?如何为 hist 中分布的头部和尾部分配不同的 bin 大小?
【发布时间】:2020-10-11 19:59:00
【问题描述】:

我正在尝试创建一个直方图,在其中我可以根据数据是位于分布的头部还是尾部,为数据分配不同的 bin 大小。

我尝试创建以下函数my_f 用作参数breaks= 的输入,但它不起作用。这是我的代码,以及我得到的错误。

x <- rnorm(1000, 10, 275)
my_f <- function(x){
  loc <- list(x[x < -500], x[x >= -500 & x <= 500], x[x > 500])
  dx <- c(5, 1, 5)
  breaks <- sapply(1:length(x), function(i) if(x[i] %in% loc[[1]])
     {seq(min(loc[[1]]), max(loc[[1]])+dx[1], dx[1])} else
       if(x[i] %in% loc[[2]]){seq(min(loc[[2]]), max(loc[[2]])+dx[2], dx[2])} else
         {seq(min(loc[[3]]), max(loc[[3]])+dx[3], dx[3])})
  return(breaks)
}

h <- hist(x, breaks = my_f)

Error in hist.default(x, breaks = my_f, plot = F) : 
  c("Invalid breakpoints produced by 'breaks(x)': 200.1702, 210.1702, ....

我也尝试不使用sapply 函数,但我没有从中得到任何结果。有关如何解决/解决此问题的任何建议?

【问题讨论】:

    标签: r histogram binning custom-function


    【解决方案1】:

    我相信你想的太复杂了,你想要的就是这个。

    my_f2 <- function(x) {
      c(seq(min(x), max(x[x < -500]), 5),
        seq(-500, 500, 1), 
        seq(min(x[x > 500]), max(x), 5), 
        max(x))
    }
    
    set.seed(666)
    x <- rnorm(1000, 10, 275)
    hist(x, my_f2)
    

    但是请注意,最后一个 bin 有点动态,因为 max(x) 没有有效地包含在 seq(min(x[x &gt; 500]), max(x), 5) 中,因此我们必须额外包含它。

    【讨论】:

    • 非常感谢!这正是我一直在寻找的,正如你正确提到的那样,我让一切变得比原来复杂得多。非常感谢您的帮助
    • @EmanueleCitera 酷,我很乐意提供帮助。在这种情况下(和往常一样)请考虑mark the answer as accepted
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 2020-07-27
    • 2018-10-12
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多