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?
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With