问题
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:
- https://shiny.rstudio.com/articles/validation.html
- 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