“empty data message” in renderTable

会有一股神秘感。 提交于 2021-02-19 08:01:55

问题


I user renderTable to show some data. However, sometimes the data table is empty, in which case I'd like to print "No data to show" or something similar. the default by renderTable is to show nothing for empty data. can this be changed? how?


回答1:


You can use a condition into a renderUi to render either a message or a "tableOutput" (you can't render directly the table)

datas <- data.frame()

shiny::runApp(list(
  ui = pageWithSidebar(
    headerPanel("Example"),
    sidebarPanel(
      selectInput("dataset", "Dataset", choices = c("iris", "datas"))
    ),
    mainPanel(
      uiOutput("ui")
    )
  ),
  server = function(input, output, session) {

    datasetInput <- reactive({
      switch(input$dataset,
             "iris" = iris,
             "datas" = datas)
    })

    output$ui <- renderUI({
      if(nrow(datasetInput()) == 0)
        return("No data to show")

      tableOutput("table")
    })

    output$table <- renderTable({
      head(datasetInput())
    })
  }
))



回答2:


I think you are looking for something like validate function.

Using example code provided by Julien:

    datas <- data.frame()

    shiny::runApp(list(

      ui = pageWithSidebar(

        headerPanel("Example"),

        sidebarPanel(
          selectInput("dataset", "Dataset", choices = c("iris", "datas"))
        ),

        mainPanel(
          tableOutput('table')
        )
      ),

      server = function(input, output, session) {

        datasetInput <- reactive({
          switch(input$dataset,
                 "iris" = iris,
                 "datas" = datas)
        })


        output$table <- renderTable({
          y <- head(datasetInput())
                validate(
                  need(nrow(y) > 0, "No Data to show")
                         )
        y
        })

      }

    ))


来源:https://stackoverflow.com/questions/22650737/empty-data-message-in-rendertable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!