Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shiny: Dynamic number of datatables

I'm using the attached code to generate sub-tables based on groups. For some reason only the last portion of the data is rendered for every table. It would be great if someone can tell me what is going wrong.

BR

enter image description here

library(shiny)
library(shinydashboard)
library(DT)
library(data.table)

tabnames <- LETTERS[1:6]

DT <- data.table(mtcars[1:30,], keep.rownames=TRUE)
DT[, grp:=rep(tabnames, each=trunc(nrow(mtcars)/length(tabnames)))]


ui = dashboardPage(
  dashboardHeader(title = "Dynamic DTs"),
  dashboardSidebar(),
  dashboardBody(
    uiOutput("tables"),
    p(),
    verbatimTextOutput("selectedCells")
  )
  )


server <- function(input, output, session) {
  output$tables <- renderUI({
    output_list <- list()
    for(i in seq(tabnames)){
      output_list[[i]] <- column(4, DT::dataTableOutput(outputId=tabnames[i]))
    }
    print(fluidRow(output_list))
    return(fluidRow(output_list))
  })


  for(i in seq(tabnames)){
    tabname <- tabnames[i]
    local({
      print(DT[grp %in% tabname, 1:3])
      output[[tabname]] <- DT::renderDataTable({
        DT[grp %in% tabname, 1:3]
      }, selection=list(mode="multiple", target="cell"))
    })
  }
  output$selectedCells <- renderPrint(input$A_cells_selected)
}

shinyApp(ui = ui, server = server)
like image 592
ismirsehregal Avatar asked Oct 25 '25 04:10

ismirsehregal


1 Answers

Ok, found a solution: needed to pass it in a separate variable:

library(shiny)
library(shinydashboard)
library(DT)
library(data.table)

tabnames <- LETTERS[1:6]

DT <- data.table(mtcars[1:30,], keep.rownames=TRUE)
DT[, grp:=rep(tabnames, each=trunc(nrow(mtcars)/length(tabnames)))]


ui = dashboardPage(
  dashboardHeader(title = "Dynamic DTs"),
  dashboardSidebar(),
  dashboardBody(
    uiOutput("tables"),
    p(),
    verbatimTextOutput("selectedCells")
  )
  )


server <- function(input, output, session) {
  output$tables <- renderUI({
    output_list <- list()
    for(i in seq(tabnames)){
      output_list[[i]] <- column(4, DT::dataTableOutput(outputId=tabnames[i]))
    }
    print(fluidRow(output_list))
    return(fluidRow(output_list))
  })


  for(i in seq(tabnames)){
    tabname <- tabnames[i]
    local({
      subDT <- DT[grp %in% tabname, 1:3]
      output[[tabname]] <- DT::renderDataTable({
        subDT
      }, selection=list(mode="multiple", target="cell"))
    })
  }
  output$selectedCells <- renderPrint(input$A_cells_selected)
}

shinyApp(ui = ui, server = server)
like image 112
ismirsehregal Avatar answered Oct 26 '25 16:10

ismirsehregal