您可以使用findInterval 获取直方图函数创建的类别。
df$cats <- findInterval(df$s, s.breaks)
这是直方图的结构
s.hist <- hist(df$s,breaks=10,plot=F)
str(s.hist)
List of 6
$ breaks : num [1:11] -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 ...
$ counts : int [1:10] 1 3 7 14 21 20 19 9 4 2
$ density : num [1:10] 0.02 0.06 0.14 0.28 0.42 0.4 0.38 0.18 0.08 0.04
$ mids : num [1:10] -2.25 -1.75 -1.25 -0.75 -0.25 0.25 0.75 1.25 1.75 2.25
$ xname : chr "df$s"
$ equidist: logi TRUE
- attr(*, "class")= chr "histogram"
注意 counts 变量的元素。这与 df$cats 上 table 的输出相同。
table(df$cats)
1 2 3 4 5 6 7 8 9 10
1 3 7 14 21 20 19 9 4 2
如果目标是使用 df$cats 构建的类别来执行计算。然后你就完成了。例如,
tapply(df$p, df["cats"], mean)
将为您的问题中每个直方图条中包含的观察结果计算 df$b 的平均值。
如果目标是为在相应类别单元格中具有相同计数的其他变量构建类别,您可以像这样将rank 与cumsum 和findInterval 一起使用。
df$catp <- findInterval(rank(df$p), cumsum(c(1, s.hist$counts, 1)))
您可以检查单元格计数是否与table 再次对齐。
table(df$catp)
1 2 3 4 5 6 7 8 9 10
1 3 7 14 21 20 19 9 4 2