【问题标题】:Groupby bins and aggregate in RR中的Groupby bins和聚合
【发布时间】:2014-08-12 13:26:24
【问题描述】:

我有像 (a,b,c) 这样的数据

a b c
1 2 1
2 3 1
9 2 2
1 6 2

其中“a”范围被分成 n(比如 3)个相等的部分,聚合函数计算 b 值(比如最大值)并在“c”处也分组。

所以输出看起来像

a_bin  b_m(c=1) b_m(c=2)
1-3     3          6
4-6     NaN        NaN
7-9     NaN        2

这是 MxN,其中 M = a bin 的数量,N = 唯一的 c 个样本或所有范围

我该如何处理?任何 R 包都可以帮助我完成吗?

【问题讨论】:

    标签: r grouping aggregate bins


    【解决方案1】:

    我会使用data.tablereshape2 的组合,它们都针对速度进行了全面优化(不使用来自apply 系列的for 循环)。

    输出不会返回未使用的 bin。

    v <- c(1, 4, 7, 10) # creating bins 
    temp$int <- findInterval(temp$a, v)
    
    library(data.table)
    temp <- setDT(temp)[, list(b_m = max(b)), by = c("c", "int")]
    
    library(reshape2)
    temp <- dcast.data.table(temp, int ~ c, value.var = "b_m")
    ## colnames(temp) <- c("a_bin", "b_m(c=1)", "b_m(c=2)") # Optional for prettier table
    ## temp$a_bin<- c("1-3", "7-9") # Optional for prettier table
    
    ##   a_bin b_m(c=1) b_m(c=2)
    ## 1   1-3        3        6
    ## 2   7-9       NA        2
    

    【讨论】:

    【解决方案2】:

    aggregatecutreshape 的组合似乎有效

    df <- data.frame(a = c(1,2,9,1),
                     b = c(2,3,2,6),
                     c = c(1,1,2,2))
    
    breaks <- c(0, 3, 6, 9)
    
    # Aggregate data
    ag <- aggregate(df$b, FUN=max,
                    by=list(a=cut(df$a, breaks, include.lowest=T), c=df$c))
    
    # Reshape data
    res <- reshape(ag, idvar="a", timevar="c", direction="wide")
    

    【讨论】:

      【解决方案3】:

      会有更简单的方法。

      如果你的数据集是dat

      res <- sapply(split(dat[, -3], dat$c), function(x) {
      a_bin <- with(x, cut(a, breaks = c(1, 3, 6, 9), include.lowest = T, labels = c("1-3", 
          "4-6", "7-9")))
      c(by(x$b, a_bin, FUN = max))
      })
      res1 <- setNames(data.frame(row.names(res), res), 
              c("a_bin", "b_m(c=1)", "b_m(c=2)"))
      row.names(res1) <- 1:nrow(res1)
      
       res1
       a_bin b_m(c=1) b_m(c=2)
      1   1-3        3        6
      2   4-6       NA       NA
      3   7-9       NA        2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-29
        • 2020-01-28
        • 2021-11-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-21
        • 2021-02-06
        相关资源
        最近更新 更多