R How to Order Columns of a Data Frame by Variable Names (Example Code)

In this post you’ll learn how to reorder data frame columns by name in R programming.

Creation of Example Data

data(mtcars)                                      # Load mtcars
head(mtcars)                                      # Head of mtcars
#                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Example: Sorting Data Frame Variables by Columns

mtcars_sort <- mtcars[ , order(names(mtcars))]    # Ordering mtcars
head(mtcars_sort)                                 # Print new mtcars
#                   am carb cyl disp drat gear  hp  mpg  qsec vs    wt
# Mazda RX4          1    4   6  160 3.90    4 110 21.0 16.46  0 2.620
# Mazda RX4 Wag      1    4   6  160 3.90    4 110 21.0 17.02  0 2.875
# Datsun 710         1    1   4  108 3.85    4  93 22.8 18.61  1 2.320
# Hornet 4 Drive     0    1   6  258 3.08    3 110 21.4 19.44  1 3.215
# Hornet Sportabout  0    2   8  360 3.15    3 175 18.7 17.02  0 3.440
# Valiant            0    1   6  225 2.76    3 105 18.1 20.22  1 3.460

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