[R] by group

Andrew Simmons @kw@|mmo @end|ng |rom gm@||@com
Mon Nov 1 22:24:06 CET 2021


I would usually use 'tapply'. It splits an object into groups, performs
some function on each group, and then (optionally) converts the input to
something simpler.
For example:


tapply(dat$wt, dat$Year, mean)  # mean by Year
tapply(dat$wt, dat$Sex , mean)  # mean by Sex
tapply(dat$wt, list(dat$Year, dat$Sex), mean)  # mean by Year and Sex


The documentation ?tapply has many more details about how this works, but
that's the basics at least. I hope this helps!

On Mon, Nov 1, 2021 at 5:09 PM Val <valkremk using gmail.com> wrote:

> 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list