Ordering variables in R alphabetically without necessarily using relocate function

I would like to order the variables in the below tibble so I have a1, a2, …d2. How can I achieve that?

library(tidyverse)

dat1 <- tibble(
  b1 = c("Math", "Kisw", "Computer", "Biology"),
  a1 = c("Science", "Geog", "Studies", "Math"),
  a2 = c("Yes", "No", "Yes", "No"),
  b2 = rnorm(4, 80, 5),
  c2 = rnorm(4, 67, 5),
  b4 = rnorm(4, 98, 5),
  d2 = rnorm(4, 23, 5),
  d1 = rnorm(4, 76, 5),
  a5 = rnorm(4, 87, 5)

)

>Solution :

It’s not tidyverse, but

dat1[sort(names(dat1))]

will work.

If you have more than 10 sequentially numbered variable names (e.g. a1 up to a20) you might want to use gtools::mixedsort() instead of sort() so that they get sorted a1, … a10, a11, …, a20 rather than lexicographically (a1, a10, a11, … , a2, a20, a3, …) (gtools::mixedsort will also work with the select() and relocate()-based answers posted by others.)

Leave a Reply