Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading