Ordering rows with datatables

2k views Asked by At

Surely this has been asked before, but I haven't been able to turn up any code that works for me. I'm working with a DataTable in R Shiny. I want to generate the DataTable and have it ordered by default on the second column rather than the first. This is what I have in server.R:

output$TabVals <- DT::renderDataTable({
  DT::datatable(TableData(), 
              options = list(pageLength = 25, 
                             searching = FALSE, 
                             paging = FALSE),   
              rownames = FALSE) %>%
      formatRound(2, digits = 0)
})

This works great. What I found other people had done was include in the options order = list(2, 'asc') (since I'm sorting on the second column and want the data ascending. When I add that line, however, the DataTable no longer displays any rows.

I put together this example to recreate the problem:

c1 <- c("a", "b", "c")
c2 <- c(1, 2, 3)
test <- cbind(c1, c2)

test1 <-  DT::datatable(test)
test2 <-  DT::datatable(test, options = list(order = list(2, 'desc')))

test1 makes a nice DataTable. test2 generates a blank table.

I tried moving the order = list(2, 'asc') to other parts of the code (eg after options, before rownames, after the pipe), but that didn't help. Thoughts appreciated!

2

There are 2 answers

2
Carl Sutton On

I am not at all sure this is what you are after, but you could try either of the following

library(data.table). 
c1 <- c("a", "b", "c")
c2 <- c(1, 2, 3)
test <- data.table(c1,c2)
setkey(test,c2)
test
# or
test[, some function in j, by = c2]

Hope that helps. I have a hunch you know more R than I.

0
Fideldue On

DT is based on javascript, so the indexing starts at 0 instead of 1. That's why your table is blank, you want to sort for a non-existent column.

So this should work:

c1 <- c("a", "b", "c")
c2 <- c(1, 2, 3)
test <- cbind(c1, c2)

test1 <-  DT::datatable(test)
test2 <-  DT::datatable(test, options = list(order = list(1, 'desc')))