The order() function in R is very useful in sorting a particular data values according to a specific variable.
Hello folks, changing the order of the values or elements present in a data frame or a vector is found to be very effective in data analysis. Hence, this R tutorial is focussed on the order() function which is used to order the data.
Table of Contents[
]
Order() = The order() function will arranges the data or orders the data based on given parameters.
1
order``(x,decreasing=F,na.last=``**NA**``)
Where,
In this section, we can try to order a simple vector having some values in it. Let’s make use of order() function to order the values as well.
This is a simple vector and now we can try to order the values.
1
2
3
4
5
#creates a vector
x<-``c``(3.5,7.8,5.6,1.1,2.9,4.4)
#orders the values in the vector in an ascending or increasing fashion
x[``order``(x)]
You will get the values arranged in the increasing fashion because by default the parameter is set as decreasing = F.
Output = 1.1 2.9 3.5 4.4 5.6 7.8
The above output shows the ascending order, now let’s order the values in a decreasing fashion.
1
2
3
4
5
#creates a vector
x<-``c``(3.5,7.8,5.6,1.1,2.9,4.4)
#orders the data in the decreasing fashion
x[``order``(x,decreasing = T)]
Output = 7.8 5.6 4.4 3.5 2.9 1.1
With the help of order() function, you can easily order the values in both increasing and decreasing fashion as well. Let’s see how it works.
Let’s create a data frame using ‘tibble’ function.
Tibble: Tibble in R is widely used to generate a data frame with random values. It may include multiple rows and columns as well.
1
2
3
4
5
6
7
8
9
#import the required package
library``(dplyr)
#creates a data frame with normal distribution values.
df<-``tibble``(
column1=``rnorm``(5,5,1.5),
column2=``rnorm``(5,5,1.5),
column3=``rnorm``(5,5,1.5),
column4=``rnorm``(5,5,1.5))
The data frame created using tibble function is shown below.
Let’s order the particular columns in this data frame.
1
2
#orders the values in the column 1
df[``order``(df$column1),]
As you can in the above output, column 1 has been sorted in increasing fashion.
Let’s see how we can order the column in a data frame as well and also using the** ‘-‘** (negative) sign to order the values in a decreasing fashion.
1
2
#orders the values [decresing the column values]
df[``order``(-df$column1),]
As you can see in the above piece of code column 1 is backed by the negative ‘-‘ sign which indicates the decreasing order. Like this method also you can change the ordering fashion instead of mentioning parameters as shown in the syntax and in the above examples.
#r programming #r #syntax