Search code examples
rsortingdata.tablealphanumericdt

Sort rows in data.table (rendered with the DT package) in alphanumeric order


I'm trying to figure out if I can sort rows in a data.table rendered with the DT package in alphanumeric order. I've searched for previous examples but, it seems like there is no way to do that. Can anyone help lead me to the right direction?


Solution

  • It is possible. The way you want to do it depends on wether you want to order your datastructure (1.) or whether you want to just sort the rendered output of your datatable() call (2.).

    1. If you want to order your data.table, follow the instructions in this SO post: Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier
    2. If you want to order only the rendered output you can use the option settings of your datatable() call as explained here https://rstudio.github.io/DT/options.html

    A small example from the source above. Sort the table by columns 2 (ascending) and 4 (descending):

    datatable(head(mtcars, 30), options = list(
      order = list(list(2, 'asc'), list(4, 'desc'))
    ))