How to use Arrange() method In R Language
For data transformation in R, we will use The arrange() method, to create an order for the sequence of the observations given. It takes a single column or a set of columns as the input to the method and creates an order for these.
The arrange() method in the tidyverse package inputs a list of column names to rearrange them in a specified order. By default, the arrange() method arranges the data in ascending order. It has the following syntax :
Syntax: arrange(col-name)
Parameter:
col-name – Name of the column.
The data frame can be supplied with a pipe operator followed by the application of arrange() method to reflect the changes.
R
# Importing tidyvverse library (tidyverse) # Creating a data frame data_frame = data.frame ( col1 = c (2,4,1,7,5,3,5,8), col2 = letters [1:8], l3 = c (0,1,1,1,0,0,0,0)) # Assigning row names rownames (data_frame) <- c ( "r1" , "r2" , "r3" , "r4" , "r5" , "r6" , "r7" , "r8" ) print ( "Data Frame" ) print (data_frame) # Arranging a single column in ascending order arr_data_frame <- data_frame %>% arrange (col1) print ( "Arranged Data Frame" ) print (arr_data_frame) |
Output:
col1 col2 col3
r1 2 a 0
r2 4 b 1
r3 1 c 1
r4 7 d 1
r5 5 e 0
r6 3 f 0
r7 5 g 0
r8 8 h 0
[1] "Arranged Data Frame"
col1 col2 col3
r3 1 c 1
r1 2 a 0
r6 3 f 0
r2 4 b 1
r5 5 e 0
r7 5 g 0
r4 7 d 1
r8 8 h 0
Explanation :
The minimum col1 value is 1, and then the largest is 8. All the col1 values in the data frame are arranged in ascending order, and the rows are shuffled accordingly. Similarly, we can arrange the data in descending order using desc() method inside arrange() method and the data frame rows are shuffled accordingly as in the below example.
The column values can also be arranged in descending order by specifying the order explicitly using the following syntax :
Syntax: arrange(desc(col-name))
R
# Importing tidyverse library (tidyverse) # Creating a data frame data_frame = data.frame ( col1 = c (2,4,1,7,5,3,5,8), col2 = letters [1:8], col3 = c (0,1,1,1,0,0,0,0)) # Assigning row names rownames (data_frame) <- c ( "r1" , "r2" , "r3" , "r4" , "r5" , "r6" , "r7" , "r8" ) print ( "Data Frame" ) # Printing data frame print (data_frame) # Arranging column in descending order arr_data_frame <- data_frame %>% arrange ( desc (col1)) print ( "Arranged Data Frame" ) print (arr_data_frame) |
Output:
col1 col2 col3
r1 2 a 0
r2 4 b 1
r3 1 c 1
r4 7 d 1
r5 5 e 0
r6 3 f 0
r7 5 g 0
r8 8 h 0
[1] "Arranged Data Frame"
col1 col2 col3
r8 8 h 0
r4 7 d 1
r5 5 e 0
r7 5 g 0
r2 4 b 1
r6 3 f 0
r1 2 a 0
r3 1 c 1
How to Transform Data in R?
In this article, we will learn how to transform data in the R programming language.
Contact Us