[R] Aggregate to find majority level of a factor

Marc Schwartz marc_schwartz at comcast.net
Thu May 31 22:32:46 CEST 2007


On Thu, 2007-05-31 at 12:25 -0700, Thompson, Jonathan wrote:
> I want to use the aggregate function to summarize data by a factor (my
> field plots), but I want the summary to be the majority level of another
> factor.
> 
>  
> For example, given the dataframe:
> 
> Plot1     big
> Plot1     big
> Plot1     small
> Plot2     big
> Plot2     small    
> Plot2     small
> Plot3     small
> Plot3     small
> Plot3     small
> 
> 
> My desired result would be:
> Plot1 big
> Plot2 small
> Plot3 small
> 
> 
> I can't seem to find a scalar function that will give me the majority
> level. 
> 
> Thanks in advance,
> 
> Jonathan Thompson

Jonathan,

Try this:

> DF
     V1    V2
1 Plot1   big
2 Plot1   big
3 Plot1 small
4 Plot2   big
5 Plot2 small
6 Plot2 small
7 Plot3 small
8 Plot3 small
9 Plot3 small


> with(DF, aggregate(V2, list(V1), function(x) names(which.max(table(x)))))
  Group.1     x
1   Plot1   big
2   Plot2 small
3   Plot3 small


See ?which.max, ?names and ?table.

HTH,

Marc Schwartz



More information about the R-help mailing list