【问题标题】:Binning data in R with the same output as in spreadsheet将 R 中的数据分箱,输出与电子表格中的相同
【发布时间】:2020-02-12 08:17:54
【问题描述】:

我有这个样本数据:

set.seed(25)

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

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

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 函数的函数,我希望它与电子表格的输出相同。

谢谢。

【问题讨论】:

    标签: r data.table binning


    【解决方案1】:

    您必须总结 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)
    

    【讨论】:

    • 如果我有很多年,即 2015 年到 2017 年的数据,我该如何改进?
    • 例如aggregate(xx$score, list(values=cut(xx$values, brks, ordered_result = TRUE), year=xx$year), length)
    猜你喜欢
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 2013-03-18
    • 2020-04-01
    相关资源
    最近更新 更多