简体   繁体   中英

Shiny reactive table based on select boxes

I have a data set that contains 2 columns as of now (which I will add to later). I want to be able to make the table change based on the selected inputs in the select boxes. I also want to have the option to use one or multiple select boxes at a time. For example, I want to see all the names with the age "20" displayed on the table. I dont know how to change the server portion to make my table reactive. I also plan to add more data and widgets, so I need to be able to add more reactive filters.

l <- NULL
l$name <- c('b','e','d','b','b','d','e')
l$age <- c(20,20,21,21,20,22,22)
l <- as.data.frame(l)
l$name <- as.character(l$name)
l$age <- as.numeric(l$age)

ui <-  fluidPage(
  titlePanel("example"),
 
  
  
   selectInput( "age2", 
                  " Select Age", 
                  choices = c("SELECT", unique(l$age))), 

   selectInput( "name2", 
                  " Select name", 
                  choices = c("SELECT", unique(l$name))),

  
 mainPanel(ui <- 
           dataTableOutput("Table1")
          
          ),

      )

server <- function(input, output, session) {
 

  
 output$Table1 <- renderDataTable(l, options = list(pageLength = 10))
  


}

One thing you should remember to do is to make your data reactive with the reactive function. Any data you plan on using and for it to be reactive, wrap it in the reactive function.

Notes: The {{value}} allows you to access the value passed from the function.

Once you wrap the l dataframe in reactive, you use parenthesis around the value anywhere you use it.

library(tidyverse)
library(shiny)

l <- NULL
l$name <- c('b','e','d','b','b','d','e')
l$age <- c(20,20,21,21,20,22,22)
l <- as.data.frame(l)
l$name <- as.character(l$name)
l$age <- as.numeric(l$age)

df <- function(data, ...) {

  map2_dfr(...names(), seq_along(...names()), \(x,y) {
    
    data <<- data |> 
      filter(.data[[x]] %in% ...elt(y) )
  }) 
  
  
  return(data)

} 
  
  
  return(data |> unique())

}

ui <-  fluidPage(
  
  titlePanel("example"),
  
  
  
  selectInput( "age2", 
               " Select Age", 
               choices = c(unique(l$age))), 
  
  selectInput( "name2", 
               " Select name", 
               choices = c(unique(l$name))),
  
  
  mainPanel(
    DT::dataTableOutput("Table1"),
    verbatimTextOutput("text")
            
  ),
  

  
)

server <- function(input, output, session) {
  
  
  data <- reactive(l)

  output$Table1 <- DT::renderDataTable(df(data(), input$age2, input$name2))
  
  
}

shinyApp(ui, server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM