Home > Back-end >  Putting column names (cut2 - brackets) in numerical order
Putting column names (cut2 - brackets) in numerical order

Time:04-24

I made a frequency table which have overlapping strata, which lead to data as follows:

dat <- structure(list(`[0,25)` = 5L, `[100,250)` = 43L, `[100,500)` = 0L, 
    `[1000,1000000]` = 20L, `[1000,1500)` = 0L, `[1500,3000)` = 0L, 
    `[25,100)` = 38L, `[25,50)` = 0L, `[250,500)` = 27L, `[3000,1000000]` = 0L, 
    `[50,100)` = 0L, `[500,1000)` = 44L, `[500,1000000]` = 0L), row.names = "Type_A", class = "data.frame")

The brackets, which are the column names of dat are in alphabetical order. I need them to be in numerical order, but I find it quite tricky.

Desired order:

[0,25), [25,50), [25,100), [50,100), ..., [3000,1000000]

What would be the best way to do this?

CodePudding user response:

Here is a bit tricky, but maybe useful way:

ord <- gsub("\\[|\\]|\\)", "", colnames(dat)) %>% 
         strsplit(",") %>% 
         lapply(as.numeric) %>% 
         lapply(sum) %>% 
         unlist %>% 
         order()

colnames(dat)[ord]
# [1] "[0,25)"         "[25,50)"        "[25,100)"       "[50,100)"      
# [5] "[100,250)"      "[100,500)"      "[250,500)"      "[500,1000)"    
# [9] "[1000,1500)"    "[1500,3000)"    "[500,1000000]"  "[1000,1000000]"
# [13] "[3000,1000000]"

dat[ord]
#       [0,25) [25,50) [25,100) [50,100) [100,250) [100,500) #[250,500) [500,1000)
#Type_A      5       0       38        0        43         0        #27         44
#       [1000,1500) [1500,3000) [500,1000000] [1000,1000000] #[3000,1000000]
#Type_A           0           0             0             20              0
  •  Tags:  
  • r
  • Related