ROY
ROY

Reputation: 270

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.

Upvotes: 1

Views: 78

Answers (3)

989
989

Reputation: 12937

Another base R attempt:

df[,order(as.numeric(lapply(strsplit(names(df),"_"),tail,1)))]

#  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

Upvotes: 0

akrun
akrun

Reputation: 887158

We can use mixedorder from gtools to order the columns

library(gtools)
df1 <- df[mixedorder(names(df))]
df1
#     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

Or if it is based only on the floating numbers

df[order(as.numeric( sub(".*_", "", 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

Upvotes: 1

Sotos
Sotos

Reputation: 51592

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

Upvotes: 1

Related Questions