Custom sorting of character in shiny DT table

I am trying to sort character columns where I need to sort as per my customization as shown below. It is working by default. But when we click on the sorting arrow, it is soring as per alphabets only. Can we not sort it as per the customization i have done

library(shiny)
library(DT)

ui <- fluidPage(
  dataTableOutput("tab")

)

server <- function(input, output, session) {
  
  table1 <- mtcars
  table1$new <- rownames(mtcars)
  table1 <- table1 %>% mutate(sort_new = ifelse(new == "Hornet 4 Drive",1,ifelse(new == "Mazda RX4 Wag",2, ifelse(new == "Mazda RX4",3,
                                                                                                                  ifelse(new == "Hornet Sportabout",4,
                                                                                                                         ifelse(new == "Valiant",5,
                                                                                                                                ifelse(new == "Datsun 710",6,7))))))) %>% arrange(desc(-sort_new))
  
  output$tab <- renderDataTable({
    datatable(head(table1, n = 6))
  })
}

shinyApp(ui, server)

Something like this?
(adapted from SO solution: r - Ordering factors in data table using DT package - Stack Overflow)

library(shiny)
library(DT)

ui <- fluidPage(
  dataTableOutput("tab")
  
)

server <- function(input, output, session) {
  
  table1 <- mtcars
  table1$new <- rownames(mtcars)
  table1 <- table1 %>% mutate(sort_new = ifelse(new == "Hornet 4 Drive",1,ifelse(new == "Mazda RX4 Wag",2, ifelse(new == "Mazda RX4",3,
                                                                                                                  ifelse(new == "Hornet Sportabout",4,
                                                                                                                         ifelse(new == "Valiant",5,
                                                                                                                                ifelse(new == "Datsun 710",6,7))))))) %>% arrange(desc(-sort_new))
  
  output$tab <- renderDataTable({
    datatable(head(table1, n = 6),
              options = list(
                columnDefs = list(
                  list(orderData=13,targets=12),
                  list(visible=FALSE,targets=13)
                  )
                )
              )
  })
}

shinyApp(ui, server)

Thanks a lot. It helps :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.