How to display data in MainPanel based on user selection in Shiny R?

廉价感情. 提交于 2019-12-04 06:40:54

问题


My dataframe looks like below, and I would like to build ShinyApp such that when user selects System from SidebarPanel only info. related to selected system gets displayed in mainpanel. Currently, below app displays entire datatable in mainpanel. I am new to shiny and I not sure how to hide datatable in mainpanel.

Is there any functionality available in Shiny ?

Provide explanation with code

DataFrame

> df <- data.frame("Users" =c('A',"B","A",'C','B'), "Date" = c('17 Mar 2019','15 Mar 2019','11 Mar 2019','20 Apr 2019',"21 Apr 2019"), "Systems" = c("Sys1", "Sys1","Sys2","Sys3","Sys4"), stringsAsFactors = FALSE)
> df
  Users        Date Systems
1     A 17 Mar 2019    Sys1
2     B 15 Mar 2019    Sys1
3     A 11 Mar 2019    Sys2
4     C 20 Apr 2019    Sys3
5     B 21 Apr 2019    Sys4

App so far..

library(shiny)
library(DT)
library(dplyr)
ui <- basicPage(
  h2("Different Systems"),
  sidebarLayout(
    sidebarPanel(
      selectInput('slct',"Select System",choices = df$Systems)
  ),
  mainPanel(
  DT::dataTableOutput("mytable")
)
)
)
server <- function(input, output) {
  #df$system<-rownames(df$Systems)
  output$mytable = DT::renderDataTable({
    df %>%
      filter(stringr::str_detect(Systems, as.character(input$slct)))

  })

}

shinyApp(ui, server)

回答1:


Option 1:

You ca use req() to ensure that input$slct must be available for the table to be displayed.

You only need to change your server code:

server <- function(input, output) {
    #df$system<-rownames(df$Systems)
    output$mytable = DT::renderDataTable({
        req(input$slct) # add this line
        df %>%
            filter(stringr::str_detect(Systems, as.character(input$slct)))

    })

}

Option 2:

You can use validate() and need make requirements and suggest user input.

server <- function(input, output) {
    #df$system<-rownames(df$Systems)
    output$mytable = DT::renderDataTable({
        validate(need(input$slct,"Please Select System")) # add this line
        df %>%
            filter(stringr::str_detect(Systems, as.character(input$slct)))

    })

}

Read those two articles for more information:

  1. https://shiny.rstudio.com/articles/validation.html
  2. https://shiny.rstudio.com/articles/req.html


来源:https://stackoverflow.com/questions/57126285/how-to-display-data-in-mainpanel-based-on-user-selection-in-shiny-r

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