0

If i have a matrix that looks like this:

        Region                    Ålder     Antal   regpop    Andel                 
   [1,] "01 Stockholms län"       "0 år"    "28474" "2377081" "0.0119785568939384"  
   [2,] "01 Stockholms län"       "1 år"    "29033" "2377081" "0.0122137192632477"  
   [3,] "01 Stockholms län"       "10 år"   "29678" "2377081" "0.0124850604586045"  
   [4,] "01 Stockholms län"       "100+ år" "524"   "2377081" "0.000220438428475933"
   [5,] "01 Stockholms län"       "11 år"   "29679" "2377081" "0.0124854811426283"  
   [6,] "01 Stockholms län"       "12 år"   "28956" "2377081" "0.0121813265934144"  
   [7,] "01 Stockholms län"       "13 år"   "28592" "2377081" "0.0120281976087479"
   [8,] "01 Stockholms län"       "14 år"   "27572" "2377081" "0.0115990999044627"  
   [9,] "01 Stockholms län"       "15 år"   "27466" "2377081" "0.0115545073979389"  
  [10,] "01 Stockholms län"       "16 år"   "26691" "2377081" "0.0112284772794869"  
  [11,] "01 Stockholms län"       "17 år"   "26004" "2377081" "0.0109394673551301"  
  [12,] "01 Stockholms län"       "18 år"   "24996" "2377081" "0.0105154178591306"  
  [13,] "01 Stockholms län"       "19 år"   "24971" "2377081" "0.0105049007585354"  
  [14,] "01 Stockholms län"       "2 år"    "29268" "2377081" "0.0123125800088428"  
  [15,] "01 Stockholms län"       "20 år"   "24777" "2377081" "0.0104232880579164"  

what should i do to order them from "0 år", "1 år", "2 år" ....."100+ år"

  • Relevant: https://stackoverflow.com/questions/20396582/order-a-mixed-vector-numbers-with-letters – Sotos Mar 11 '20 at 15:58

2 Answers2

2

The gtools::mixedsort function can help here

x <- c("0 år", "1 år", "10 år", "100+ år", "11 år", "12 år", "13 år", 
  "14 år", "15 år", "16 år", "17 år", "18 år", "19 år", "2 år", 
  "20 år")

gtools::mixedsort(x)
#  [1] "0 år"    "1 år"    "2 år"    "10 år"   "11 år"   "12 år"   "13 år"   "14 år"  
#  [9] "15 år"   "16 år"   "17 år"   "18 år"   "19 år"   "20 år"   "100+ år"

If the object you shared is a matrix named data, then you could do

data[gtools::mixedorder(data[["Ålder"]]),]
MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

Here is a base R option. Extract the digits from the string using gsub and then convert to a numeric allowing us to reorder numerically. I have created a mock matrix just as an example. Perhaps if you could provide the actual matrix by using dput i.e. dput(matrix) then paste the output into your question, that would help people give more specific answers

x <- c("0 år", "1 år", "10 år", "100+ år", "11 år", "12 år", "13 år", 
       "14 år", "15 år", "16 år", "17 år", "18 år", "19 år", "2 år", 
       "20 år")

y <- 1:length(x)

mat <- matrix(c(x, y), ncol = 2)

mat[order(as.numeric(gsub("[^0-9.]", "", mat[,1]))),]
hammoire
  • 341
  • 1
  • 2
  • 10