Multiple functions in a single tapply or aggregate statement

前端 未结 4 442
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 22:27

Is it possible to include two functions within a single tapply or aggregate statement?

Below I use two tapply statements and two aggregate statements: one for mean a

4条回答
  •  抹茶落季
    2020-12-08 23:05

    If you'd like to use data.table, it has with and by built right into it:

    library(data.table)
    myDT <- data.table(my.Data, key="animal")
    
    
    myDT[, c("mean", "sd") := list(mean(weight), sd(weight)), by=list(age, sex)]
    
    
    myDT[, list(mean_Aggr=sum(mean(weight)), sd_Aggr=sum(sd(weight))), by=list(age, sex)]
         age    sex mean_Aggr   sd_Aggr
    1: adult female     96.0  3.6055513
    2: young   male     76.5  2.1213203
    3: adult   male     91.0  1.4142136
    4: young female     84.5  0.7071068
    

    I used a slightly different data set so as to not have NA values for sd

提交回复
热议问题