r - Ordering Column names with suffixes -


this question has answer here:

i have dataframe columns named as_of_date_1, as_of_date_2, etc uptil as_of_date_40. want columns arranged in ascending order of numbers, default seems treating column names character strings (rightly so) , hence gets arranged as_of_date_1, as_of_date_11,as_of_date_12...etc, followed as_of_date_2 series , on. how 1 this?

you can use mixedorder gtools package:

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

result:

  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 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -