简体   繁体   中英

Order a data frame using character and numeric columns

I have a dataframe:

 df <- data.frame(c(name = "FORT DUNCAN", "DETAR HOSPITAL", "CYPRESS FAIRBANKS","MISSION REGIONAL", "Test"), rate = c(8.0,8.7,8.7,8.1,8.9))
colnames(df) = c("name","rate")
ordered_df <- df[order(df[,2]),]

               name rate
1       FORT DUNCAN  8.0
4  MISSION REGIONAL  8.1
2    DETAR HOSPITAL  8.7
3 CYPRESS FAIRBANKS  8.7
5              Test  8.9

I can clearly order the dataframe by the rate variable. However, If two rates are similar then I want to order by name. ie Detar Hospital and Cypress Fairbanks have the same rate of 8.7. Therefore, I want Cypress Fairbanks to move up and Detar Hospital to move down and Test should remain at its place (The last place according to the rate)... Any ideas???

Cheers

Since order accepts many variables via ... you can do the following:

> df[order(df[,2],df[,1] ),]
               name rate
1       FORT DUNCAN  8.0
4  MISSION REGIONAL  8.1
3 CYPRESS FAIRBANKS  8.7
2    DETAR HOSPITAL  8.7
5              Test  8.9

I think I fixed it by:

ordered_df <- df[order(df$rate, df$name),]

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM