mstich mstich -3 years ago 81
R Question

Sort data frame by two columns (with condition)

I have the following data frame in R:

DataTable <- data.frame( Name = c("Nelle","Alex","Thomas","Jeff","Rodger","Michi"), Age = c(17, 18, 18, 16, 16, 16), Grade = c(1,5,3,2,2,4) )

Name Age Grade
1 Nelle 17 1
2 Alex 18 5
3 Thomas 18 3
4 Jeff 16 2
5 Rodger 16 2
6 Michi 16 4


Now ill will sort this data frame by its
Age
column. No problem so far:

DataTable_sort_age <- DataTable[with(DataTable, order(DataTable[,2])),]

Name Age Grade
4 Jeff 16 2
5 Rodger 16 2
6 Michi 16 4
1 Nelle 17 1
2 Alex 18 5
3 Thomas 18 3


There are more persons in the
Name
columns that have the same age and they should be sorted alphabetically. If the condition, that more than one person is at the same age, is true the data frame should be sorted alphabetically by
Name
. The output should look like this:

Name Age Grade
1 Jeff 16 2
2 Michi 16 2
3 Rodger 16 4
4 Nelle 17 1
5 Alex 18 5
6 Thomas 18 3


Hope you can help me by sorting the data frame alphabetically.

Answer Source

As per @Stezzo 's comment updating the answer

Just add, DataTable[, 1] in the order function

DataTable[order(DataTable[,2], DataTable[, 1]),]

#    Name Age Grade
# 4   Jeff  16     2
# 6  Michi  16     4
# 5 Rodger  16     2
# 1  Nelle  17     1
# 2   Alex  18     5
# 3 Thomas  18     3

Remember, the order in which parameters are passed matters. It would first sort the DataTable dataframe w.r.t 2nd column and in case of a tie it would consider the second parameter which is the first column.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download