Calculate the mean by group

后端 未结 5 1031
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 04:42

I have a large data frame that looks similar to this:

df <- data.frame(dive = factor(sample(c("dive1","dive2"), 10, replace=TRUE)),
            


        
5条回答
  •  日久生厌
    2020-11-21 05:33

    Adding alternative base R approach, which remains fast under various cases.

    rowsummean <- function(df) {
      rowsum(df$speed, df$dive) / tabulate(df$dive)
    }
    

    Borrowing the benchmarks from @Ari:

    10 rows, 2 groups

    10 million rows, 10 groups

    10 million rows, 1000 groups

提交回复
热议问题