I'm using shiny and the renderDataTable function from the DT package to show a table in my webapp. When sorting, it seems to be treating the numbers as strings, ordering by first digit then second and so on i.e what should sort to 1, 2, 5, 100, 250 would be sorted to 1, 100, 2, 250, 5
I've tried specifying colClasses when reading the csv, but doesn't seem to work.
server.R shown, my ui.R is just a dataTableOutput
library(DT)
library(dplyr)
date <- format(Sys.Date() - 1, '%Y_%m_%d')
date2 <- format(Sys.Date() - 2, '%Y_%m_%d')
# Read data in
tab1 <- read.csv(paste0(date, '_tabs.csv'), stringsAsFactors = FALSE, colClasses = c('character', rep('integer', 9)))
tab1 <- na.omit(tab1)
tab2 <- read.csv(paste0(date2, '_tabs.csv'), stringsAsFactors = FALSE, colClasses = c('character', rep('numeric', 9)))
# Ensuring both tables have matching values for country
tab3 <- tab2[tab2$X %in% tab1$X, ]
missingr <- setdiff(tab1$X, tab3$X)
for (j in missingr) {
tab3 <- rbind(tab3, rep(0, length(tab1)))
tab3[nrow(tab3), 1] <- j
}
# Sorting by country and creating a new dataframe of differences
Country <- tab1$X
tab1 <- arrange(tab1, X)
tab3 <- arrange(tab3, X)
tab1 <- tab1[, !(names(tab1) %in% 'X')]
tab3 <- tab3[, !(names(tab3) %in% 'X')]
tab2 <- tab1 - tab3
# Adding total column and country column to dataframes
c1 <- c('Total', colSums(tab1))
c2 <- c('Total', colSums(tab2))
rownames(tab2) <- Country
tab2 <- data.frame(Country, tab2)
tab1 <- data.frame(Country, tab1)
tab1 <- tab1[tab1$total > 100, ]
tab2 <- tab2[tab2$Country %in% tab1$Country, ]
tab1 <- rbind(tab1, c1)
tab2 <- rbind(tab2, c2)
shinyServer(function(input, output) {
output$tab1 <- renderDataTable({tab1},
rownames = FALSE, options = list(lengthMenu = list(c(20, 10, -1), c('20', '10', 'All')),
initComplete = JS("function(settings, json) {","$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});","}"),
autoWidth = TRUE,
columnDefs = list(list(width = '200px', targets = "_all"))
))
output$tab2 <- renderDataTable({tab2},
rownames = FALSE, options = list(lengthMenu = list(c(20, 10, -1), c('20', '10', 'All')),
initComplete = JS("function(settings, json) {","$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});","}"),
autowidth = TRUE,
columnDefs = list(list(width = '200px', targets = "_all"))
))
}
)
renderDataTabledoes not order the table by default. The section 4.1 of rstudio.github.io/DT/options.html explains theorder-option. - user5029763stron the tables you've created. It will tell you what sort of data you have And adding the output to your question would be helpfull. - user5029763