Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reorder column names by last character

Tags:

r

I have df with following colname:

colname(df) gives:

"SUBJID" "EoT_A"  "EoT_B"  "EoT_C"  "EoT_D"  "PR_A"   "PR_B"   "PR_C"   "PR_D"  
"PD_A"   "PD_B"   "PD_C"   "PD_D"   "CR_A"   "CR_B"   "CR_C"   "CR_D"

I would like to reorder colname like:

"SUBJID" 
"EoT_A" "PR_A" "PD_A" "CR_A"
"EoT_B" "PR_B" "PD_B" "CR_B"
"EoT_C" "PR_C" "PD_C" "CR_C"
"EoT_D" "PR_D" "PD_D" "CR_D"            

would there be a smart way to achieve this?

like image 403
D. Shin Avatar asked Sep 14 '25 05:09

D. Shin


2 Answers

You could use dplyr::ends_with, e.g.

df |> 
  dplyr::select(SUBJID, dplyr::ends_with(LETTERS[1:4])) |> 
  colnames()

 [1] "SUBJID" "EoT_A"  "PR_A"   "PD_A"   "CR_A"   "EoT_B"  "PR_B"   "PD_B"  
 [9] "CR_B"   "EoT_C"  "PR_C"   "PD_C"   "CR_C"   "EoT_D"  "PR_D"   "PD_D"  
[17] "CR_D" 
like image 148
Julian Avatar answered Sep 16 '25 20:09

Julian


I don't know how smart it is, but you can do

df[c(1, order(sapply(strsplit(names(df), '_'), function(x) rev(x)[1])[-1]) + 1)]

for example, if your data frame looks like this:

df
#>   SUBJID EoT_A EoT_B EoT_C EoT_D PR_A PR_B PR_C PR_D PD_A PD_B PD_C PD_D CR_A CR_B CR_C CR_D
#> 1      1     2     3     4     5    6    7    8    9   10   11   12   13   14   15   16   17

Then the code puts your data into the required order:

df[c(1, order(sapply(strsplit(names(df), '_'), function(x) rev(x)[1])[-1]) + 1)]
#>   SUBJID EoT_A PR_A PD_A CR_A EoT_B PR_B PD_B CR_B EoT_C PR_C PD_C CR_C EoT_D PR_D PD_D CR_D
#> 1      1     2    6   10   14     3    7   11   15     4    8   12   16     5    9   13   17
like image 24
Allan Cameron Avatar answered Sep 16 '25 18:09

Allan Cameron