What is the shortest and flexible tidyverse way to reorder columns by position?
I have some tibble and want to insert the last column to the n-th position.
I'm interested in a one-liner if it's possible.
Here’s one approach. I’ll use as my example moving the last column of mtcars
to the 6th position.
If you know the name of the column you want to move:
mtcars %>% select(1:5, carb, everything())
If you only know that it’s the last column:
mtcars %>% select(1:5, length(mtcars), everything())
Edited to add: the tidyselect
helpers give you lots of options. I could have also used last_col()
, above.
6 Likes
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
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