[R] Collapsing a factor in R

Roger D. Peng rpeng at jhsph.edu
Wed Jan 14 19:21:21 CET 2004


Will aggregate() do what you want?

-roger

Scott Norton wrote:
> I'm trying to collapse the following table along the sub-group factor.  In
> this case, collapsing means taking the average ages within a subgroup and
> creating a new table.  I seem to be running into trouble trying to create
> this new data frame. I can use the ave() function to find averages within a
> subgroup but how do I maintain the Group/Gender factors after collapsing?
> (see bottom table) Can anyone help??
> 
> Thanks in advance!!
> 
> Here's the starting point (table)
> 
> Age   Group  SubGroup	Gender
> 12	g1	a	f
> 32	g1	a	f
> 81	g1	a	f
> 63	g1	b	m
> 24	g1	b	m
> 24	g1	b	m
> 70	g1	c	f
> 82	g1	c	f
> 71	g1	c	f
> 61	g1	c	f
> 25	g2	d	m
> 29	g2	d	m
> 43	g2	e	f
> 17	g2	e	f
> 42	g2	e	f
> 55	g2	e	f
> 52	g2	f	f
> 19	g2	f	f
> 12	g2	f	f
> 
> The following is what I'm trying to achieve (as a new dataframe)
> 
> AvgAgeSubgroup	Group	Subgroup	Gender
> 41.67			g1	a		f
> 37			g1	b		m
> 71			g1	c		f
> 27			g2	d		m
> 39.25			g2	e		f
> 27.67			g2	f		f
> 
> Can anyone help?
> 
> -Scott
> 
> 
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list