'Dynamically added values in shiny

I have app that enable user to choose a letter from prepared table of letters and values and visualize values from the table.

GUI is dynamical and user will choose one or more letters.

I would like user output store chosen values and then filter from the table values according to chosen letters.

But this error occurs

Warning: Error in match: 'match' requires vector arguments

library(shiny)
require(ggplot2)
        
# Define UI for application
ui <- fluidPage(
    titlePanel("Sample app"),
    sidebarPanel(

          selectInput("letter", "Choose letter:", LETTERS),
          uiOutput("inputs"),
      actionButton("addInput","Add letter")
    ),
        mainPanel(
           plotOutput("letterPlot")
        )
  )
server <- function(input, output) {

  table <- data.frame(LETTER = LETTERS, value = rep(sample(1:length(LETTERS)), length(LETTERS)))
  ids <<- NULL

  observeEvent(input$addInput,{
    print(ids)
    if (is.null(ids)){
      ids <<- 1
    }else{
      ids <<- c(ids, max(ids)+1)
    }
    output$inputs <- renderUI({
      tagList(
        lapply(1:length(ids),function(i){
          
          fluidRow(
            br(),
            selectInput(paste0("letter",ids[i]), "Choose letter:", LETTERS))
        })
      )
    })
  })
  values <- reactiveValues()
  # Get ids for textboxes
  txtbox_ids <- sapply(1:length(ids),function(i){
    paste("letter",ids[i],sep="")
  })
  # Get values
  for(i in 1:length(txtbox_ids)){
   val <- reactive({  values[[i]] <- input[[ txtbox_ids[i] ]] })
  }
  
  datatable <- reactive({
    
    table <- table[table[["LETTER"]] %in% val,]
    
  })
   
  output$letterPlot <-  renderPlot({
    
    tmp <- datatable()
    ggplot2::ggplot(data=tmp, aes(x=LETTER, y=value)) +
    geom_point()
  })
}

# Run the application 
shinyApp(ui = ui, server = server)


Solution 1:[1]

Here is my proposition :

library(shiny)
require(ggplot2)

# Define UI for application
ui <- fluidPage(
  titlePanel("Sample app"),
  sidebarPanel(
    
    selectInput("letter", "Choose letters:", LETTERS,multiple=T)
  ),
  mainPanel(
    plotOutput("letterPlot")
  )
)
server <- function(input, output) {
  
  table <- data.frame(LETTER = LETTERS, value = sample(1:length(LETTERS)))
  
  table_filtered <- reactive(table[table$LETTER %in% input$letter,])

  output$letterPlot <-  renderPlot({
    ggplot2::ggplot(data=table_filtered(), aes(x=LETTER, y=value)) +
      geom_point()
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

Is that OK to you ?

I had to make it from scratch.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Levon Ipdjian