Sort data frame by two columns (with condition)
Solution 1
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.
Solution 2
in addition to @Ronak Shah answer you can also use arrange
of dplyr
.
It looks a bit simpler to me.
arrange(DataTable,Age,Name)
gives
Name Age Grade
1 Alex 16 3
2 Jeff 16 2
3 Michi 16 4
4 Rodger 16 2
5 Nelle 17 1
6 Alex 18 5
7 Thomas 18 4
Here, it first sorts by Age
then Name
and you can add more variables so on.
mstich
Updated on June 09, 2022Comments
-
mstich almost 2 years
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 byName
. 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.
-
Stefano Lombardi over 8 yearsThis works:
DataTable[order(DataTable[,"Age"], DataTable[,"Name"]), ]
. In my opinion you don't have to usewith
. If for some reason you have to do it, please explain why. P.S.: less is more when coding.