[R] How to Calculate the Mean by Multiple Groups in R

Gabor Grothendieck ggrothend|eck @end|ng |rom gm@||@com
Tue Oct 24 17:13:42 CEST 2023


A variation is to remove Well and then we can use dot to refer to the
remaining columns.

  aggregate(cbind(OD, ODnorm)  ~ . , subset(df, select = - Well), mean)


On Tue, Oct 24, 2023 at 8:32 AM Luigi Marongiu <marongiu.luigi using gmail.com> wrote:
>
> Hello,
> I have a data frame with different groups (Time, Target, Conc) and
> each entry has a triplicate value of the measurements OD and ODnorm.
> How can I merge the triplicates into a single mean value?
> I tried the following:
> ```
> df = data.frame(Time=rep(1, 9), Well=paste("A", 1:9, sep=""),
>                 OD=c(666, 815, 815, 702, 739, 795, 657, 705, 663),
>                 Target=rep("BACT", 9),
>                 Conc=c(1,1,1,2,2,2,3,3,3),
>                 ODnorm=c(9, 158, 158,  45,  82, 138,   0,  48,   6),
>                 stringsAsFactors = FALSE)
> aggregate(.~ODnorm, df, mean)
>
> > aggregate(.~ODnorm, df, mean)
>   ODnorm Time Well OD Target Conc
> 1      0   NA   NA NA     NA   NA
> 2      6   NA   NA NA     NA   NA
> 3      9   NA   NA NA     NA   NA
> 4     45   NA   NA NA     NA   NA
> 5     48   NA   NA NA     NA   NA
> 6     82   NA   NA NA     NA   NA
> 7    138   NA   NA NA     NA   NA
> 8    158   NA   NA NA     NA   NA
>
>  aggregate(cbind(Time, Target, Conc) ~ ODnorm, df, mean)
>   ODnorm Time Target Conc
> 1      0   NA     NA   NA
> 2      6   NA     NA   NA
> 3      9   NA     NA   NA
> 4     45   NA     NA   NA
> 5     48   NA     NA   NA
> 6     82   NA     NA   NA
> 7    138   NA     NA   NA
> 8    158   NA     NA   NA
> ```
>
> Thank you.
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list