How to Reorder Rows of a data.table in R (Example Code)
This page shows how to sort the rows of a data.table in R programming.
Setting up the Example
install.packages("data.table") # Install & load data.table library("data.table") |
install.packages("data.table") # Install & load data.table library("data.table")
my_df <- data.table(A = c(2, 2, 3, 2, 1, 3), # Construct new data.table B = c("x", "a", "f", "f", "a", "x")) my_df # Display data.table in RStudio console # A B # 1: 2 x # 2: 2 a # 3: 3 f # 4: 2 f # 5: 1 a # 6: 3 x |
my_df <- data.table(A = c(2, 2, 3, 2, 1, 3), # Construct new data.table B = c("x", "a", "f", "f", "a", "x")) my_df # Display data.table in RStudio console # A B # 1: 2 x # 2: 2 a # 3: 3 f # 4: 2 f # 5: 1 a # 6: 3 x
Example: Sorting Rows of data.table Using setorder() Function
setorder(my_df) # Sorting data.table my_df # Displaying updated data.table # A B # 1: 1 a # 2: 2 a # 3: 2 f # 4: 2 x # 5: 3 f # 6: 3 x |
setorder(my_df) # Sorting data.table my_df # Displaying updated data.table # A B # 1: 1 a # 2: 2 a # 3: 2 f # 4: 2 x # 5: 3 f # 6: 3 x