Home > Enterprise >  Reorder r dataframe columns with where column names have mixed letters and numbers
Reorder r dataframe columns with where column names have mixed letters and numbers

Time:12-27

I have a table similar to the following

Subject Day -1 Day 1 Day -2
00001 1 3 5
00002 2 4 6

I was wondering how I can sort the column names with "Subject" first, then Day -2, Day -1, finally Day 1 in numeric order? I have many more columns than this and may need to do this on multiple tables so would appreciate an automated answer.

CodePudding user response:

With gtools::mixedsort:

dat[c("Subject", gtools::mixedsort(names(dat)[-1]))]

output

  Subject Day -2 Day -1 Day 1
1       1      5      1     3
2       2      6      2     4

Or in dplyr, with num_range and relocate:

dat %>% 
  relocate(Subject, num_range("Day ", -2, 2))

CodePudding user response:

To complete @Maël answers. We could use also mixedorder also from gtools:

library(gtools)
library(dplyr)
df %>%
  select(1, mixedorder(names(.)[-1]) 1)
# A tibble: 2 × 4
  Subject `Day -2` `Day -1` `Day 1`
  <chr>      <dbl>    <dbl>   <dbl>
1 00001          5        1       3
2 00002          6        2       4
  • Related