Sort Rows of Data Frame Based on Vector in R (Example Code)

In this R article you’ll learn how to rearrange data frame rows according to a vector.

Creation of Example Data

Creation of Example Data

my_df <- data.frame(Col1 = 1:6,          # Constructing data frame in R
                    Col2 = LETTERS[1:6])
my_df                                    # Showing example data frame in RStudio console
#   Col1 Col2
# 1    1    A
# 2    2    B
# 3    3    C
# 4    4    D
# 5    5    E
# 6    6    F
my_vector <- c(5, 1, 3, 2, 6, 4)         # Constructing vector in R
my_vector                                # Showing example vector in RStudio console
# 5 1 3 2 6 4

Example: Applying match() Function to Order Data Frame Rows Based on Vector

my_df[match(my_vector, my_df$Col1), ]    # Rearranging example data frame
#   Col1 Col2
# 5    5    E
# 1    1    A
# 3    3    C
# 2    2    B
# 6    6    F
# 4    4    D

Related Articles

You may find some related R tutorials in the following list.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top