[R] sorting factor levels by data frequency of levels

Greg Snow Greg.Snow at intermountainmail.org
Mon Nov 19 20:32:11 CET 2007


?reorder

Try:

> newstate <- reorder(state,state, length)

Or

> newstate <- reorder(state,state, function(x) -length(x) )

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at intermountainmail.org
(801) 408-8111
 
 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Shoaaib Mehmood
> Sent: Friday, November 16, 2007 3:22 AM
> To: r-help at stat.math.ethz.ch; r-help at r-project.org
> Subject: [R] sorting factor levels by data frequency of levels
> 
> using an example from r online help
> 
> > state <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa",
>     "qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas",
>     "sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa",
>     "sa", "act", "nsw", "vic", "vic", "act")
> >statefac<-factor(state)
> 
> now if i use levels function to print factor levels they are 
> shown sorted by alphabetical order. the output is shown below
> 
> >levels(statefac)
> [1] "act" "nsw" "nt" "qld" "sa" "tas" "vic" "wa"
> 
> I WANT THE FACTOR LEVELS TO BE SORTED IN ORDER OF DESCENDING 
> DATA FREQUENCY IN EACH LEVEL. IN OTHER WORDS I WANT THE LEVEL 
> WHICH HAS THE HIGHEST FREQUENCY IN STATE TO APPEAR FIRST, 
> FOLLOWED BY ONE WHICH HAS THE SECOND HIGHEST FREQUENCY AND SO ON.
> 
> Any help will be appreciated
> 
> 
> --
> Regards,
> Rana Shoaaib Mehmood
> 
> ______________________________________________
> R-help at r-project.org 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.
> 



More information about the R-help mailing list