如何用 R 平均两个(或多个直方图)
How to average two (or multiple histograms) with R
有人能告诉我如何用 R 计算两个直方图的平均值吗?
我遇到了 HistogramTools 包和 AddHistograms
函数:
h1<-hist(na.omit(a[,1]),breaks = 100,plot=F)
h2<-hist(na.omit(a[,2]),breaks = 100,plot=F)
> AddHistograms(h1,h2)
Error in .AddManyHistograms(x, main = main) :
Histograms must have identical breakpoints for this operation.
但我总是有同样的错误 Histograms must have identical breakpoints for this operation
?有人可以解释为什么吗?
我猜 a[1] 和 a[2] 的长度不一样 ,与 h1 和 h2 的输出相同(即 我不h1 和 h2 之间的“breaks”、“mids”、“counts”的长度相同 ).
你能告诉我如何使用这个函数或其他任何 R 函数对我的两个直方图进行平均吗?
按照以下步骤操作:
- 创建
h1
和h2
, - 组合并排序中断向量,
- 保留唯一值
- 并添加直方图。
对于问题中的(不可重现的)示例,
h1 <- hist(na.omit(a[,1]), plot = FALSE)
h2 <- hist(na.omit(a[,2]), plot = FALSE)
brks <- sort(c(h1$breaks, h2$breaks))
brks <- unique(brks)
h1 <- hist(na.omit(a[,1]), breaks = brks, plot = FALSE)
h2 <- hist(na.omit(a[,2]), breaks = brks, plot = FALSE)
h12 <- AddHistograms(h1, h2)
plot(h12)
另请注意,na.omit
并不是真正需要的,hist
无论如何都会丢弃它们。