【问题标题】:R how to bin weighted dataR如何对加权数据进行分箱
【发布时间】:2012-09-20 12:37:48
【问题描述】:

您好,我正在尝试在 ggplot 中绘制直方图,但我的数据没有所有值,只有值和出现次数。

value=c(1,2,3,4,5,6,7,8,9,10)
weight<-c(8976,10857,10770,14075,18075,20757,24770,14556,11235,8042)
df <- data.frame(value,weight)
df
   value weight
1      1   8976
2      2  10857
3      3  10770
4      4  14075
5      5  18075
6      6  20757
7      7  24770
8      8  14556
9      9  11235
10    10   8042

任何人都会知道如何对值进行分箱或如何绘制分箱值的直方图。
我想得到一些看起来像

    bin  weight
1   1-2   19833
2   3-4   24845
...

【问题讨论】:

    标签: r binning


    【解决方案1】:

    我会添加另一个变量来指定分箱,然后

    df$group <- rep(c("1-2", "3-4", "5-6", "7-8", "9-10"), each = 2)
    

    使用 ggplot 绘制它。

    ggplot(df, aes(y = weight, x = group)) + stat_summary(fun.y="sum", geom="bar")
    

    【讨论】:

    • 最好使用一个因子:cut(..., breaks=..., labels=...)
    【解决方案2】:

    这是一种将数据合并的方法:

    df$bin <- findInterval(df$value,seq(1,max(df$value),2))
    result <- aggregate(df["weight"],df["bin"],sum)
    # get your named bins automatically without specifying them individually
    result$bin <- tapply(df$value,df$bin,function(x) paste0(x,collapse="-"))
    
    # result
       bin weight
    1  1-2  19833
    2  3-4  24845
    3  5-6  38832
    4  7-8  39326
    5 9-10  19277
    
    # barplot it (base example since Roman has covered ggplot)
    with(result,barplot(weight,names.arg=bin))
    

    【讨论】:

      【解决方案3】:

      只需扩展您的数据:

      value=c(1,2,3,4,5,6,7,8,9,10)
      weight<-c(8976,10857,10770,14075,18075,20757,24770,14556,11235,8042)
      dat = rep(value,weight)
      # plot result
      histres = hist(dat)
      

      如果您想要直方图数据的详细信息,则 histres 包含一些可能有用的信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-22
        相关资源
        最近更新 更多