Order rows by type of character

53 Views Asked by At

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"))
3

There are 3 best solutions below

0
r2evans On BEST ANSWER

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),]
0
geek45 On

First, define the custom order.
Then reorder.

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


custom_order <- c(rev(sort(dt[!Resultado %like% "<"][order(-as.numeric(gsub(",", ".", Resultado)))]$Resultado)),
                  "<LCM",
                  "<LDM")

dt <- dt[order(match(Resultado, custom_order))]

> print(dt)
   Resultado
1:      5,89
2:      3,12
3:      1,39
4:      0,25
5:      <LCM
6:      <LCM
7:      <LDM
8:      <LDM
0
stefan_aus_hannover On

This solution uses a custom function and DPLYR

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

library(dplyr)
customSort <- function(x) {
  dt1 <- x |> 
    filter(grepl(',',Resultado)) |>
    arrange(desc(Resultado))
  dt2 <- x |> 
    filter(grepl('<',Resultado)) |>
    arrange(Resultado)
  dt <- rbind(dt1,dt2)
}
dt3 <- customSort(dt)