[R] by group
PIKAL Petr
petr@p|k@| @end|ng |rom prechez@@cz
Tue Nov 2 12:23:44 CET 2021
Hi
Although you got several answers, simple aggregate was omitted.
> with(dat, aggregate(wt, list(Year=Year, Sex=Sex), mean))
Year Sex x
1 2001 F 12.00000
2 2002 F 13.33333
3 2003 F 12.00000
4 2001 M 15.00000
5 2002 M 16.33333
6 2003 M 15.00000
you can reshape the result
> library(reshape2)
Warning message:
package 'reshape2' was built under R version 4.0.4
> dcast(res, Year~Sex)
Using x as value column: use value.var to override.
Year F M
1 2001 12.00000 15.00000
2 2002 13.33333 16.33333
3 2003 12.00000 15.00000
Cheers
Petr
> -----Original Message-----
> From: R-help <r-help-bounces using r-project.org> On Behalf Of Val
> Sent: Monday, November 1, 2021 10:08 PM
> To: r-help using R-project.org (r-help using r-project.org) <r-help using r-project.org>
> Subject: [R] by group
>
> Hi All,
>
> How can I generate mean by group. The sample data looks like as follow,
> dat<-read.table(text="Year Sex wt
> 2001 M 15
> 2001 M 14
> 2001 M 16
> 2001 F 12
> 2001 F 11
> 2001 F 13
> 2002 M 14
> 2002 M 18
> 2002 M 17
> 2002 F 11
> 2002 F 15
> 2002 F 14
> 2003 M 18
> 2003 M 13
> 2003 M 14
> 2003 F 15
> 2003 F 10
> 2003 F 11 ",header=TRUE)
>
> The desired output is,
> M F
> 2001 15 12
> 2002 16.33 13.33
> 2003 15 12
>
> 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.
More information about the R-help
mailing list