2017-09-12 1 views
3

Ich habe einen Datenrahmen mit Spalten mit den Namen As_of_date_1, As_of_date_2, usw. bis As_of_date_40. Ich möchte die Spalten in aufsteigender Reihenfolge der Zahlen angeordnet werden, aber der Standard scheint die Spaltennamen als Zeichenfolgen zu behandeln (zu Recht) und wird daher als As_of_date_1, As_of_date_11, As_of_date_12 ... usw. angeordnet, gefolgt von der As_of_date_2 Serien und so weiter. Wie macht man das?Reihenfolge Spaltennamen mit Suffixen

+1

'as.numeric (gsub ("\\ D +", "", "As_of_date_40")) 'wird dir die Nummer bringen, dann sortiere danach –

Antwort

2

Sie können mixedorder von gtools Paket verwenden:

library(gtools) 

colnames = paste("As_of_date_", 1:20, sep = "") 
colnames = sort(colnames) # Wrong order 
# [1] "As_of_date_1" "As_of_date_10" "As_of_date_11" "As_of_date_12" "As_of_date_13" 
# [6] "As_of_date_14" "As_of_date_15" "As_of_date_16" "As_of_date_17" "As_of_date_18" 
# [11] "As_of_date_19" "As_of_date_2" "As_of_date_20" "As_of_date_3" "As_of_date_4" 
# [16] "As_of_date_5" "As_of_date_6" "As_of_date_7" "As_of_date_8" "As_of_date_9" 

df = as.data.frame(matrix(sample(1:5, 10*20, replace = TRUE), nrow = 10, ncol = 20)) 
names(df) = colnames 

df[, mixedorder(names(df))] 

Ergebnis:

As_of_date_1 As_of_date_2 As_of_date_3 As_of_date_4 As_of_date_5 As_of_date_6 As_of_date_7 
1   3   3   5   8   3   3   5 
2   8   2   9   7   4   7   10 
3   5   8   9   8   7   5   9 
4   9   9   8   1   4   8   9 
5   10   4   5   5   2   2   2 
    As_of_date_8 As_of_date_9 As_of_date_10 As_of_date_11 As_of_date_12 As_of_date_13 
1   2   2    1   10    9    9 
2   7   8    6    5    3    7 
3   4   1    9    7    1    7 
4   7   5    6    6    4   10 
5   4   6    5    2   10    7 
    As_of_date_14 As_of_date_15 As_of_date_16 As_of_date_17 As_of_date_18 As_of_date_19 
1    8   10    5    2    2    1 
2    6   10    8    5    3    5 
3    6    7    3    5    5    8 
4    3    8    4    4    3    2 
5    2    1    3    2    9    6 
    As_of_date_20 
1    7 
2    1 
3    4 
4    3 
5    9 
Verwandte Themen