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
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.
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)), ]
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:")
## [1] "Original dataframe:"
print(E)
## N S A Q
## 1 Jhon 10.0 2 yes
## 2 Hialy 9.5 1 no
## 3 Albert 12.2 2 yes
## 4 James 11.0 4 no
## 5 Delma 8.0 1 no
print("dataframe after sorting 'N' and 'S' columns:")
## [1] "dataframe after sorting 'N' and 'S' columns:"
E = E[with(E, order(N, S)), ]
print(E)
## 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