LuisMoncayo
LuisMoncayo

Reputation: 125

sort columns based in names R

I need to sort the following data.frame in R based on its columns name:

L1 L10 L11 L12           L13       L14 L15        L16          L17 L18 L19 L2 L20 L21        L22 L23 L24         L25
1  1.00000000   0   0   0  0.000000e+00 0.0000000   0 0.00000000 0.000000e+00   0   0  0   0   0 0.00000000   0   0 0.000000000

The ordered columns must look like:

L1 L2 L10 L11 L12 L13 L14 L15 L16 L17 L18 L19 L20 L21 L22 L23 L24 L25

Upvotes: 0

Views: 59

Answers (1)

s_baldur
s_baldur

Reputation: 33498

You could do sort(names(df)) but the issue is that L2 comes after L10 (lexicographical sorting for strings).

One thing we could do is adding a white space (left padding) in front of the strings length 2 which makes sure they come before when sorted.

df[order(sprintf("%*s", 3, names(df)))]


  L1 L2 L10 L11 L12 L13 L14 L15 L16 L17 L18 L19 L20 L21 L22 L23 L24 L25
1  1  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

A stringr alternative:

df[order(stringr::str_pad(names(df), 3, side = "left", pad = " "))]

PS.

If you have longer variable names, 3 should be replace by max(nchar(names(df)).

Upvotes: 1

Related Questions