Calculate the mean by group

后端 未结 5 1013
没有蜡笔的小新
没有蜡笔的小新 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:38

    We already have tons of options to get mean by group, adding one more from mosaic package.

    mosaic::mean(speed~dive, data = df)
    #dive1 dive2 
    #0.579 0.440 
    

    This returns a named numeric vector, if needed a dataframe we can wrap it in stack

    stack(mosaic::mean(speed~dive, data = df))
    
    #  values   ind
    #1  0.579 dive1
    #2  0.440 dive2
    

    data

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

提交回复
热议问题