How to sort alphabetically rows of a data frame?

13,483

One solution with dplyr:

library(dplyr)
df %>%
  group_by(x) %>%
  arrange(c)

Or as @Akrun mentions in the comments below just

df %>%
  arrange(x,c)

if you are not interested in grouping. Depends on what you want.

Output:

Source: local data frame [5 x 2]
Groups: x

  x c
1 2 A
2 2 D
3 3 B
4 3 C
5 5 E

There is another solution in base R but it will only work if your x column is ordered as is, or if you don't mind changing the order it has:

> df[order(df$x, df$c), , drop = FALSE]
  x c
2 2 A
1 2 D
4 3 B
3 3 C
5 5 E
Share:
13,483
EnginO
Author by

EnginO

Updated on August 21, 2022

Comments

  • EnginO
    EnginO over 1 year

    I am tring to sort c alphabetically if x[i]== x[i+1]. I used order() function but it changes the x column as well. I want to order the entire row:

     best <- function(state){
     HospitalName<-vector()
     StateName<-vector()
     HeartAttack<-vector()
    
      k<-1
    
      outcome<-read.csv("outcome-of-care-measures.csv",colClasses= "character")
    
     temp<-(outcome[,c(2,7,11,17,23)])
    
    for (i in 1:nrow(temp)){
     if(identical(state,temp[i,2])==TRUE){
        HospitalName[k]<-temp[i,1]
        StateName[k]<-temp[i,2]
        HeartAttack[k]<-as.numeric(temp[i,4])
        k<-k+1
         }}
        frame<-data.frame(cbind(HospitalName,StateName,HeartAttack))
    
    
      library(dplyr)
      frame %>%
      group_by(as.numeric(as.character(frame[,3]))) %>%
      arrange(frame[,1])
        }
    
      Output:
                                   HospitalName StateName HeartAttack
     1              FORT DUNCAN MEDICAL CENTER        TX         8.1
     2         TOMBALL REGIONAL MEDICAL CENTER        TX         8.5
     3        CYPRESS FAIRBANKS MEDICAL CENTER        TX         8.7
     4                  DETAR HOSPITAL NAVARRO        TX         8.7
     5                  METHODIST HOSPITAL,THE        TX         8.8
     6         MISSION REGIONAL MEDICAL CENTER        TX         8.8
     7  BAYLOR ALL SAINTS MEDICAL CENTER AT FW        TX         8.9
     8       SCOTT & WHITE HOSPITAL-ROUND ROCK        TX         8.9
     9         THE HEART HOSPITAL BAYLOR PLANO        TX           9
     10    UT SOUTHWESTERN UNIVERSITY HOSPITAL        TX           9
    ..                                    ...       ...         ...
    Variables not shown: as.numeric(as.character(frame[, 3])) (dbl)
    

    Output does not contain the HeartAttack Column and I do not understand why?