Search code examples
rdataframedplyr

Order rows by type of character


I need to sort a rows of a column character type, showing first the numbers sorted from highest to lowest and then the characters with "<" in a specific order: first "<LCM" and then "<LDM".

From:

enter image description here

To:

enter image description here

data.table::data.table(Resultado = c("1,39", "5,89", "3,12", "0,25", "<LCM", "<LDM", "<LDM", "<LCM"))

Solution

  • If your numbers are ,-decimal numbers, then we can do

    quux[order(-suppressWarnings(as.numeric(sub(",", ".", Resultado))), Resultado),]
    #    Resultado
    #       <char>
    # 1:      5,89
    # 2:      3,12
    # 3:      1,39
    # 4:      0,25
    # 5:      <LCM
    # 6:      <LCM
    # 7:      <LDM
    # 8:      <LDM
    

    If instead they are distinct ,-separated numbers and you are only sorting on the first, then we can do

    quux[order(-suppressWarnings(as.numeric(sub(",.*", "", Resultado))), Resultado),]