R Program to sort a given data frame by multiple column(s)

How to sort a given data frame by multiple column(s)

Here we explain how to write an R program to sort a given data frame by multiple column(s). Here we are using a built-in function order() for this sorting. The order() function helps to returns a permutation. It rearranges its first argument into ascending or descending order, breaking ties by further arguments. The syntax of order() is like

order(…, na.last = TRUE, decreasing = FALSE,
      method = c("auto", "shell", "radix")) 

Here dots(....) is the sequence of numeric, complex, character, or logical vectors or a classed R object. If na.last is TRUE, missing values in the data are put last; if FALSE, they are put first and the next is the method to be used here partial matches are allowed.

How to sort a given data frame by multiple column(s) in the R program

Below are the steps used in the R program to sort a given data frame by multiple column(s). In this R program, we directly give the data frame to a built-in function. Here we are using variables E, N, S, A, Q for holding different types of vectors. Call the function data.frame() for creating data frame. Finally, Sort a given data frame by multiple column(s) by calling like E[with(E, order(N, S)), ]

ALGORITHM

STEP 1: Assign variables E,N,S,A,Q with vector values 

STEP 2: First print original vector values

STEP 3: Sort a given data frame by multiple column(s) by E[with(E, order(N, S)), ]

STEP 4: Assign the result data frame into E

STEP 5: Print the final data frame

 

R Source Code

                                          E = data.frame(
N = c('Jhon', 'Hialy', 'Albert', 'James', 'Delma'),
S = c(10, 9.5, 12.2, 11, 8),
A = c(2, 1, 2, 4, 1),
Q = c('yes', 'no', 'yes', 'no', 'no')
)
print("Original dataframe:")
print(E)
print("dataframe after sorting 'N' and 'S' columns:")
E = E[with(E, order(N, S)), ]
print(E)
                                      

OUTPUT

[1] "Original dataframe:"
     name    score attempts qualify
1  Jhon       10        2     yes
2  Hialy      9.5       1     no
3  Albert     12.2      2     yes
4  James      11        4     no
5  Delma      8         1     no

[1] "dataframe after sorting 'N' and 'S' columns:"
       N    S A   Q
3 Albert 12.2 2 yes
5  Delma  8.0 1  no
2  Hialy  9.5 1  no
4  James 11.0 4  no
1   Jhon 10.0 2 yes