Outputing N tables in shiny, where N depends on the data

后端 未结 1 1649
忘掉有多难
忘掉有多难 2021-01-03 08:50

I have a shiny app in which I would like to print multiple tables. The catch is, I do not know how many tables I will have in advance - it depends on the data.

相关标签:
1条回答
  • 2021-01-03 09:17

    I started from the comment with link Dieter made to my question (R Shiny - add tabPanel to tabsetPanel dynamically (with the use of renderUI)). The principle is the same - generate HTML with all the tables in Server.R and then display it with uiOutput() in Ui.R. The difference is, that I could not find a function in shiny package, that would be analogous to the tabPanel(), that generates the HTML in the given example.

    But I was able to use xtable() to generate the HTML and passed it some extra arguments for the tables to look like expected in shiny framework when rendered.

    Example of a function, that generates HTML for an arbitrary number of tables:

    tabelize <- function(variables, arg2, ...) {
    
      tables <- list() # create a list to hold all tables
    
      for (variable in variables) { # go through all possible values of variables
        table <- function_that_returns_a_data_frame(variable, arg2, ...)
        tables[[as.character(variable)]] <- 
          # save table into slot in created list
          # print table as HTML with additional formatting options
          print(xtable(table, caption=paste("Variable:", variable)),
                type="html",
                html.table.attributes='class="data table table-bordered table-condensed"',
                caption.placement="top")
      }
      return(lapply(tables, paste)) # return HTML tables pasted together
    }
    

    Call this function in Server.R (with some additional options) and assign to an output$ slot:

    output$tables <- renderUI({
      out <- tabelize(variables, arg2, ...) 
      # additional options to make rendering possible
      return(div(HTML(out),class="shiny-html-output"))
     })
    

    Do an uiOutput() of it in Ui.R:

        ... code        
        uiOutput("tables")
        ... code
    

    If there's a better way, please comment.

    0 讨论(0)
提交回复
热议问题