Was hoping someone can help sort a column by absolute value in a Shiny app in the datatable() function? Tried multiple methods (dplyr, arrange, etc) but for some reason it's not clicking with me. It's a three column datatable, trying to sort column 2/val2 by the absolute value.
table_stage <- reactive ({
tbl <- datatable(tabledat(),
rownames = FALSE,
options = list(
columnDefs = list(list(className = "dt-center", targets = 2)),
order = list(list(2, "asc"))
)) %>%
formatRound("val", 2) %>%
formatRound("val2", 2)
return(tbl)
})
This is definitely wrong, did not work at all.
table_stage <- reactive ({
tbl <- datatable(tabledat(),
rownames = FALSE,
options = list(
columnDefs = list(list(className = "dt-center", targets = 2)),
order = list(list((arrange(abs(2)), "desc"))
)) %>%
formatRound("val", 2) %>%
formatRound("val2", 2)
return(tbl)
})
CodePudding user response:
The code runs without problems when using dataTableOutput
in a UI context and renderDataTable
in the Server function.
This script works with order by mpg (the first column in the example table) and if mtcars
is a data frame, it works too.
library(data.table)
library(shiny)
library(dplyr)
library(DT)
if (interactive()) {
ui <- fluidPage(
dataTableOutput("table")
)
#optional test data
tabledat <- data.table::as.data.table(mtcars)
server <- function(input, output) {
output$table <-
renderDataTable({
tabledat %>%
datatable(
rownames = FALSE,
options = list(
columnDefs = list(list(className = "dt-center", targets = 2)),
order = list(list(1, "asc"))
)
)
},
)
}
shinyApp(ui, server)
}
CodePudding user response:
You need to use the render
option:
library(DT)
js <- "
function(data, type, row, meta) {
if(type === 'sort') {
data = Math.abs(data);
}
return data;
}
"
mydata <- as.data.frame(
matrix(runif(40, -10000, 10000), nrow = 10, ncol = 4)
)
datatable(
mydata,
options = list(
"columnDefs" = list(
list(
"targets" = 1,
"render" = JS(js)
)
)
)
)