Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break ties with order function in R

Tags:

sorting

r

I have a data frame with 2 columns. I have ordered them using order() function

data<-data[order(data$Mortality),]
head(data)

                       Hospital.Name     Mortality
 FORT DUNCAN MEDICAL CENTER                      8.1
 TOMBALL REGIONAL MEDICAL CENTER                 8.5
 DETAR HOSPITAL NAVARRO                          8.7
 CYPRESS FAIRBANKS MEDICAL CENTER                8.7
 MISSION REGIONAL MEDICAL CENTER                 8.8
 METHODIST HOSPITAL,THE                          8.8

3rd and 4th positions are ties (Mortality = 8.7 for both). I want to break the tie with alphabetical order in data$Hospital.Name so that "CYPRESS FAIRBANKS" is 3rd and "DETAR HOSPITAL" as 4th.

like image 206
user1989607 Avatar asked Jan 18 '13 07:01

user1989607


People also ask

What does the order function do in R?

order() in R The numbers are ordered according to its index by using order(x) . Here the order() will sort the given numbers according to its index in the ascending order.

How do you order in ascending order in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

What is the use of order function?

Description. order returns a permutation which rearranges its first argument into ascending or descending order, breaking ties by further arguments. sort. list is the same, using only one argument.


1 Answers

Use data$Hospital.Name as second argument in order:

R> data <- data[order(data$Mortality, data$Hospital.Name), ]
R> data
                     Hospital.Name Mortality
1       FORT DUNCAN MEDICAL CENTER       8.1
2  TOMBALL REGIONAL MEDICAL CENTER       8.5
4 CYPRESS FAIRBANKS MEDICAL CENTER       8.7
3           DETAR HOSPITAL NAVARRO       8.7
6           METHODIST HOSPITAL,THE       8.8
5  MISSION REGIONAL MEDICAL CENTER       8.8
like image 164
rcs Avatar answered Oct 14 '22 19:10

rcs