r - Dynamic column alignment in DT datatable -
i have larger datatable output varying number of columns, chose in widget. dynamically right align columns,but found solution if number of columns fixed. hoping adjust reference in target= command make dynamic. somehow not work , not output when number of columns smaller default reference. read somewhere reactive statements not work datatable options. attached mwe.
rm(list=ls()) library(shiny) library(datasets) library(datatable) dt<-data.table(matrix(abs(rnorm(100,sd=100000)),nrow=10)) server<-shinyserver(function(input, output) { # return requested dataset columns <- reactive({ switch(input$columns, all= c("v1","v2","v3","v4","v5","v6","v7","v8","v9","v10"), left= c("v1","v2","v3","v4","v5"), right= c("v6","v7","v8","v9","v10")) }) # show table output$view <- dt::renderdatatable( format(dt[,.sd,.sdcols=columns()],digits = 0,scientific=f), option=list(columndefs=list(list(targets=0:(length(columns())-1), class="dt-right"))) ) }) library(shiny) # define ui dataset viewer application ui<-shinyui(fluidpage( # application title titlepanel("shiny text"), # sidebar controls select dataset , specify # number of observations view sidebarlayout( sidebarpanel( selectinput("columns", label = h3("select columns"), choices = list("all columns" = "all", "left side" = "left", "right side" = "right"), selected = "all") ), # show summary of dataset , html table # requested number of observations mainpanel( dt::datatableoutput("view") ) ) )) runapp(list(ui=ui,server=server))
datatable options not reactive in sense can't change options without redrawing entire table, if willing redraw table isn't problem see below:
if change server function should work:
server<-shinyserver(function(input, output) { # return requested dataset columns <- reactive({ switch(input$columns, all= c("v1","v2","v3","v4","v5","v6","v7","v8","v9","v10"), left= c("v1","v2","v3","v4","v5"), right= c("v6","v7","v8","v9","v10")) }) # reactive datatable rdt <- reactive({ dt::datatable(format(dt[,.sd,.sdcols=columns()],digits=0,scientific=false), option=list(columndefs=list( list(targets=seq_len(length(columns()))-1, class="dt-right")))) }) # show table output$view <- dt::renderdatatable( rdt() ) })
i creating reactive datatable
responds columns()
, redraws table correct columndef
. if had lot of data slow.
Comments
Post a Comment