-4

I have a very simple dataframe in R:

x <- data.frame("SN" = 1:7, "Age" = c(21,15,22,33,21,15,25), "Name" = c("John","Dora","Paul","Alex","Bud","Chad","Anton"))

My goal is to sort the dataframe by the Age and the Name. I am able to achieve this task partially if i type the following command:

x[order(x[, 'Age']),] 

which returns:

  SN Age  Name
2  2  15  Dora
6  6  15  Chad
1  1  21  John
5  5  21   Bud
3  3  22  Paul
7  7  25 Anton
4  4  33  Alex

As you can see the dataframe is order by the Age but not the Name.

Question: how can i order the dataframe by the age and name at the same time? This is what the result should look like

  SN Age  Name
6  6  15  Chad
2  2  15  Dora
5  5  21   Bud
1  1  21  John
3  3  22  Paul
7  7  25 Anton
4  4  33  Alex

Note: I would like to avoid to use additional packages but using just the default ones

Federico Gentile
  • 5,650
  • 10
  • 47
  • 102

1 Answers1

2

With dplyr:

library(dplyr)
x %>%
   arrange(Age, Name)


  SN Age  Name
1  6  15  Chad
2  2  15  Dora
3  5  21   Bud
4  1  21  John
5  3  22  Paul
6  7  25 Anton
7  4  33  Alex


x[with(x, order(Age, Name)), ]

 SN Age  Name
6  6  15  Chad
2  2  15  Dora
5  5  21   Bud
1  1  21  John
3  3  22  Paul
7  7  25 Anton
4  4  33  Alex
DSGym
  • 2,807
  • 1
  • 6
  • 18