2017-09-12 7 views
3

As_of_date_1, As_of_date_2 등의 열이있는 데이터 프레임이 있습니다. As_of_date_40입니다. 나는 열의 오름차순으로 배열을 원하지만, 기본값은 열 이름을 문자열로 취급하는 것처럼 보이므로 As_of_date_1, As_of_date_11, As_of_date_12 ... 등으로 배열되고 그 다음에 As_of_date_2이옵니다. 시리즈 등등. 어떻게하면됩니까?접미어가있는 열 이름 순서

+1

'as.numeric (GSUB ("\\ D +", "", "As_of_date_40")) '너에게 숫자를 줄 것이고, 그걸 따라 정렬해라. –

답변

2

당신은 gtools 패키지에서 mixedorder를 사용할 수 있습니다

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))] 

결과 :

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