使用与电子表格中相同的输出对 R 中的数据进行分箱

Binning data in R with the same output as in spreadsheet

我有这个示例数据:

set.seed(25)

xx <- data.table(
  year = 2015,
  values = iris$Sepal.Length,
  score = sample(1:8, nrow(iris), replace = TRUE))

实际数据包含很多年和行。我想使用 base R 中的 cut() 函数对 values 列进行分组,但结果与 LibreOffice Calc 生成的结果不同(即使在 MS Office Excel) 枢轴。这是我到目前为止所做的:

brks <- seq(0, ceiling(max(xx$values)), 0.5)
xx[, bins := cut(values, brks, ordered_result = TRUE)]
xx_binned <- dcast(xx, bins ~ year, length, value.var = "values")
xx_binned <- melt(xx_binned, id.vars = "bins", value.name = "value")

我从0开始,所以如果我使用不同的数据,它会保持一致。在电子表格中,我也从 0 作为起始编号开始。

以上代码的结果是这样的:

     bins   variable value
1   (4,4.5] 2015     5
2   (4.5,5] 2015     27
3   (5,5.5] 2015     27
4   (5.5,6] 2015     30
5   (6,6.5] 2015     31
6   (6.5,7] 2015     18
7   (7,7.5] 2015     6
8   (7.5,8] 2015     6

这是 LibreOffice Calc 的结果:

values  2015
4-4.5   15
4.5-5   106
5-5.5   100
5.5-6   142
6-6.5   148
6.5-7   95
7-7.5   25
7.5-8   27

我怎样才能让它一样呢?我正在编写一个将电子表格工具转换为 R 函数的函数,我希望它与电子表格的输出相同。

谢谢。

你必须总结 score 而不是案例的数量才能得出相同的值。

aggregate(xx$score, list(cut(xx$values, brks, right=FALSE, ordered_result = TRUE)), sum)
#  Group.1   x
#1 [4,4.5)  15
#2 [4.5,5) 106
#3 [5,5.5) 100
#4 [5.5,6) 142
#5 [6,6.5) 148
#6 [6.5,7)  95
#7 [7,7.5)  25
#8 [7.5,8)  27

或更新您的代码:

library(data.table)
xx <- data.table(xx)
xx[, bins := cut(values, brks, right=FALSE, ordered_result = TRUE)]
dcast(xx, bins ~ year, sum, value.var = "score")

数据:

set.seed(25)

xx <- data.frame(
  year = 2015,
  values = iris$Sepal.Length,
  score = sample(1:8, nrow(iris), replace = TRUE))
brks <- seq(0, ceiling(max(xx$values)), 0.5)