one way is the following: tb <- table(state) statefac <- factor(state, levels = names(tb[order(tb, decreasing = TRUE)]))
I hope it helps. Best, Dimitris ---- Dimitris Rizopoulos Ph.D. Student Biostatistical Centre School of Public Health Catholic University of Leuven Address: Kapucijnenvoer 35, Leuven, Belgium Tel: +32/(0)16/336899 Fax: +32/(0)16/337015 Web: http://med.kuleuven.be/biostat/ http://www.student.kuleuven.be/~m0390867/dimitris.htm ----- Original Message ----- From: "Shoaaib Mehmood" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]>; <r-help@r-project.org> Sent: Friday, November 16, 2007 11:21 AM 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@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. > Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm ______________________________________________ R-help@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.