Reorder columns

tidyverse
code
Author

Ravi C

Published

March 1, 2023

There are several methods to change the order of columns in R. While the select function from dplyr is a common way to do it, we will also explore other functions that can be used to rearrange columns.

To demonstrate these methods, we will use the “us_rent_income” dataset from the tidyverse package. To rearrange columns using the select function, we can explicitly specify the order in which we want our columns to appear.

us_rent_income |> head()
# A tibble: 6 x 5
  GEOID NAME    variable estimate   moe
  <chr> <chr>   <chr>       <dbl> <dbl>
1 01    Alabama income      24476   136
2 01    Alabama rent          747     3
3 02    Alaska  income      32940   508
4 02    Alaska  rent         1200    13
5 04    Arizona income      27517   148
6 04    Arizona rent          972     4
us_rent_income |>
  select(GEOID, estimate, moe, NAME, variable) |>
  head()
# A tibble: 6 x 5
  GEOID estimate   moe NAME    variable
  <chr>    <dbl> <dbl> <chr>   <chr>   
1 01       24476   136 Alabama income  
2 01         747     3 Alabama rent    
3 02       32940   508 Alaska  income  
4 02        1200    13 Alaska  rent    
5 04       27517   148 Arizona income  
6 04         972     4 Arizona rent    

Alternatively, we can use the everything function from tidyselect to select our preferred order, with the exception of columns that we have explicitly specified.

We can shorten this up and little bit using everything from tidyselect, this way we select our prefered order.

  1. GEOID
  2. estimate
  3. moe
  4. everything else
us_rent_income |>
  select(GEOID, estimate, moe, everything()) |>
  head()
# A tibble: 6 x 5
  GEOID estimate   moe NAME    variable
  <chr>    <dbl> <dbl> <chr>   <chr>   
1 01       24476   136 Alabama income  
2 01         747     3 Alabama rent    
3 02       32940   508 Alaska  income  
4 02        1200    13 Alaska  rent    
5 04       27517   148 Arizona income  
6 04         972     4 Arizona rent    

If we want to select only the numeric columns and rearrange them, we can use the relocate function from dplyr by specifying the location where the selected columns should be placed. In the example given, we move the numeric columns to be after the “GEOID” column.

us_rent_income |>
  relocate(where(is.numeric), .after = GEOID) |>
  head()
# A tibble: 6 x 5
  GEOID estimate   moe NAME    variable
  <chr>    <dbl> <dbl> <chr>   <chr>   
1 01       24476   136 Alabama income  
2 01         747     3 Alabama rent    
3 02       32940   508 Alaska  income  
4 02        1200    13 Alaska  rent    
5 04       27517   148 Arizona income  
6 04         972     4 Arizona rent