Search code examples
r

reorder column names by last character


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?


Solution

  • 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"