[英]R how to bin weighted data
嗨,我正在尝试在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
...
这是一种分类数据的方法:
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))
我会添加另一个指定binning的变量然后
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")
只需扩展您的数据:
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包含一些可能有用的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.