ROY ROY - 2 months ago 18
R Question

Reorder columns by a number embedded in their names

I have dataset which has following column names:

df

X100_TT_7.1 X50_TT_1.1 X60_TT_2.1 X80_TT_4.1 X70_TT_3.1 X85_FTT_5.1 X90_TT_6.1
0.08 0.06 0.84 0.95 0.89 0.91 0.86


I want to rearrange column in below show manner i.e. as per 1.1 to 7.1 in colnames:

df

X50_TT_1.1 X60_TT_2.1 X70_TT_3.1 X80_TT_4.1 X85_FTT_5.1 X90_TT_6.1 X100_TT_7.1
0.06 0.84 0.89 0.95 0.91 0.86 0.08


I have tried to solve the same using order and substr functions but did not get the solution.

Answer

Via base R,

df[order(sub("^.*(.*)_", "\\1", names(df)))]
#  X50_TT_1.1 X60_TT_2.1 X70_TT_3.1 X80_TT_4.1 X85_FTT_5.1 X90_TT_6.1 X100_TT_7.1
#1       0.06       0.84       0.89       0.95        0.91       0.86        0.08