Re: [R] Aggregate to find majority level of a factor

From: Mike Lawrence <Mike.Lawrence_at_dal.ca>
Date: Thu, 31 May 2007 17:43:25 -0300

This should do the trick. Also labels ties with NA.

a=as.data.frame(cbind(c(1,1,1,2,2,2,3,3,3,4,4),c ('big','big','small','big','small','small','small','small','small','big' ,'small')))
a$V2=factor(a$V2)

maj=function(x){

	y=table(x)
	z=which.max(y)
	if(sum(y==max(y))==1){
		return(names(y)[z])
	}else{
		return(NA)
	}

}

aggregate(a$V2,list(a$V1),maj)

On 31-May-07, at 4:25 PM, 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
>
> ______________________________________________
> R-help_at_stat.math.ethz.ch mailing list
> 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.

--
Mike Lawrence
Graduate Student, Department of Psychology, Dalhousie University

Website: http://myweb.dal.ca/mc973993
Public calendar: http://icalx.com/public/informavore/Public

"The road to wisdom? Well, it's plain and simple to express:
Err and err and err again, but less and less and less."
	- Piet Hein

______________________________________________
R-help_at_stat.math.ethz.ch mailing list
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.
Received on Thu 31 May 2007 - 21:40:40 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 31 May 2007 - 22:31:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.