Reorder columns by position

Updated 2021-05-28

dplyr 1.0.0 introduced relocate, a specialized function for moving columns.

Learn more at

Examples

library(dplyr)
df <- tibble(w = 0, x = 1, y = "a", z = "b")

df %>% relocate(y, z)
#> # A tibble: 1 x 4
#>   y     z         w     x
#>   <chr> <chr> <dbl> <dbl>
#> 1 a     b         0     1
df %>% relocate(where(is.character))
#> # A tibble: 1 x 4
#>   y     z         w     x
#>   <chr> <chr> <dbl> <dbl>
#> 1 a     b         0     1

If you want to move columns to a different position use .before or .after:

df %>% relocate(w, .after = y)
#> # A tibble: 1 x 4
#>       x y         w z    
#>   <dbl> <chr> <dbl> <chr>
#> 1     1 a         0 b
df %>% relocate(w, .before = y)
#> # A tibble: 1 x 4
#>       x     w y     z    
#>   <dbl> <dbl> <chr> <chr>
#> 1     1     0 a     b

If you want to move columns to the right hand side use last_col()

df %>% relocate(w, .after = last_col())
#> # A tibble: 1 x 4
#>       x y     z         w
#>   <dbl> <chr> <chr> <dbl>
#> 1     1 a     b         0

Created on 2021-05-27 by the reprex package (v2.0.0)

1 Like