Drop menu for shiny app

Hi,
I have a problem to set up a drop menu in my shiny app. I want to select a specific category in the first column of my dataset. My actual code is:

server <- output$table <- DT::renderDataTable({
selectedBrand <- input$check2
temp <- as.data.frame(database)
temp[which(temp$Compound %in% selectedBrand),]
})
ui <- tabPanel("Correlation",
sidebarPanel(
selectInput(inputId = "Compound", label = 'Select compound:',choices = c("x", "y", "z")),
actionButton("calculate", label = "Calculate")
),
mainPanel(
plotOutput('cor')
)
)

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Schermata 2021-04-13 alle 14.47.37

Ok, this is my database and I want to calculate correlation from column B to column G but in relation to the compound. So I want a drop menu to select compound before calculating correlation.

Thanks

Hi, if you want to choose specific compound

compoundnames<-reactive({
x<-read.csv("name.csv")
names<-x[,1]
})

selectInput(inputId = "Compound", label = 'Select compound:',choices = names)

this is a simple example which you can refine according to your need.
also you will have to use the same Id i.e. input$Compund while using it.

So, this is my complete code but don't work. I want to select the compound before calculating correlation. I don't understand where is my mistake.

shinyServer(
  function(input,output){

    col_min <- reactive({
      min = input$valore1
    })
    
    col_max <- reactive({
      max = input$valore2
    })
    
    ### FILE UPLOAD ###
    
     tableData <- reactive({
      inFile <- input$file1
      
      if (!is.null(inFile)){
        read_excel(input$file1$datapath)
      } else {
        mtcars
      }
    })
    
    output$table1 = renderTable(tableData())
    
    colonne <- reactive({ 
      database <- tableData()
      data_size <- ncol(database)
      returnValue(data_size)
    })
 
    output$my_output_data <- renderText({colonne()})
   
     observeEvent(input$z2a, {
    updateCheckboxGroupInput(
      session = session, inputId = "check2", choices = sort(unique(database$`Compound`), decreasing = T), selected = input$check2
    )
    })
    #### CORRELATION ###
    observeEvent(input$calcola_gap, {
      intervallo <- col_min():col_max()
      df_data_cor<-tableData()[intervallo]
      df_data_cor_scale<-scale(df_data_cor)
      
      #observeEvent(input$z2a, {
       # updateCheckboxGroupInput(
        #  session = session, inputId = "check2", choices = sort(unique(database$`Compound`), decreasing = T), selected = input$check2
        #)
      #})
      output$table <- DT::renderDataTable({
        selectedBrand <- input$check2 
        temp <- as.data.frame(database) 
        temp[which(temp$`Compound` %in% selectedBrand),] 
      })
      
      output$cor<-renderPlot({
        corrplot(
          df_data_cor,
          method = "pie", 
          order = "hclust", 
          type = "lower"
        )
      })
    })
    
  })
shinyUI(
  fluidPage(theme = shinytheme("united"),
            navbarPage(
              "Correlation Analysis",
              tabPanel("Dataset",
                       sidebarPanel(
                         fileInput('file1', 'Choose Excel file (.xlsx):',
                                   accept = c(".xlsx")
                         ),
                         sidebarPanel(
                           selectInput(inputId = "Compound", label = 'Select compound:',choices = c("FM140/1", "FM140/0", "FM157/1")),
                           actionButton("Calculate", label = "Calculate")
                         ),
                         h4("Tuning pre-analisi"),
                         h5("Column number of database is:"),
                         uiOutput("my_output_data"),
                         numericInput("valore1", label = h5("Start column is:"),min = 1,value = 1),
                         numericInput("valore2", label = h5("End column is:"),min = 1,value = 11),
                         br()
                       ),
                       
                       mainPanel(
                         tableOutput("table1")
                       )
              ), 
              tabPanel("Correlation",
                       #sidebarPanel(
                        # selectInput(inputId = "Compound", label = 'Select compound:',choices = c("x", "y", "z")),
                         #actionButton("Calculate", label = "Calculate")
                       #),
                       mainPanel(
                         plotOutput('cor')
                       )
              ) 
            ) 
  ) 
)

what is a compound in the context of mtcars example you provided ?

For example, in mtcars compound could be the brand's name of the car (merc, toyota, mazda)

ok, so I looked at it again, but im sorry its quite disorganised to work with...
For example what is check2 ? you are updating it, but you haven't placed it.
Can you not simplify this down to the essentials ?

This is already reduced to the essentials, check2 is just a test but does't work. My idea is to create an app where I can upload an Excel file, select the compound (or brand in mtcars database) and select the column where calculate correlation (for example, in mtcars I want to select only the last five column).

I rewrite the code and it can calculate correlation for all the compound, but the initial selection doesn't work. So the single selection of the compound doesn't work, I can't calculate correlation for every compound.

shinyServer(
  function(input,output){
    
    col_min <- reactive({
      min = input$valore1
    })
    
    col_max <- reactive({
      max = input$valore2
    })
    tableData <- reactive({
      inFile <- input$file1
      
      if (!is.null(inFile)){
        read_excel(input$file1$datapath)
      } else {
        mtcars
      }
    })
    
    output$table1 = renderTable(tableData())
    
    colonne <- reactive({ 
      database <- tableData()
      data_size <- ncol(database)
      returnValue(data_size)
    })
    
    output$my_output_data <- renderText({colonne()})
  
    function(input, output) {
      output$result <- renderText({
        paste("You chose", input$state)
      })
    }
    
    colonne <- reactive({ 
      database <- tableData()
      data_size <- ncol(database)
      returnValue(data_size)
    })
    
    output$my_output_data <- renderText({colonne()})
  ###correlation
    observeEvent(input$calculate_cor, {
      intervall <- col_min():col_max()
      df_data_cor<-tableData()[intervall]
      df_data_cor_scale<-cor(df_data_cor)
      
      output$cor<-renderPlot({
        corrplot(df_data_cor_scale,
                     method = "pie")
      })
    })
      })  


shinyUI(
  fluidPage(theme = shinytheme("united"),
            navbarPage(
              "Correlation Analysis",
              tabPanel("Dataset",
                       sidebarPanel(
                         fileInput('file1', 'Choose Excel file (.xlsx):',
                                   accept = c(".xlsx")
                         ),
                         selectInput("Compound", "Choose a Compound:",
                                     c("x", "y", "z"))
                         ),
                       h5("Column numer:"),
                       uiOutput("my_output_data"),
                       numericInput("valore1", label = h5("Start column:"),min = 1,value = 1),
                       numericInput("valore2", label = h5("End column:"),min = 1,value = 11),
                       
                         textOutput("result"),
              ),
                       #####correlation                   
              tabPanel("Correlation",
                                sidebarPanel(
                                  h5("Correlation."),
        
                                  actionButton("calculate_cor", label = "Calculate"),
                                ),
                       mainPanel(
                         plotOutput('cor')
                       )
          
                       )
              
                       )
           
            )
  )

p.s. please note that I declare mylibraries when I reprex, also I take care to make it so my code can simply be copy and pasted and run

I hope this solution helps you, I think Shiny is great :slight_smile:

library(corrplot)
library(shiny)
library(tidyverse)


ui<-(
  fluidPage(
            navbarPage(
              "Correlation Analysis",
              tabPanel("Dataset",
                       sidebarPanel(
                         fileInput('file1', 'Choose Excel file (.xlsx):',
                                   accept = c(".xlsx")
                         ),
                        uiOutput("filterSelector")
                       ),
                       h5("Column numer:"),
                       uiOutput("my_output_data"),
                       numericInput("valore1", label = h5("Start column:"),min = 1,value = 1),
                       numericInput("valore2", label = h5("End column:"),min = 1,value = 11),
                       
                       textOutput("result"),
                       tableOutput("table1")
              ),
              #####correlation                   
              tabPanel("Correlation",
                       sidebarPanel(
                         h5("Correlation."),
                         
                         actionButton("calculate_cor", label = "Calculate"),
                       ),
                       mainPanel(
                         plotOutput('cor')
                       )
                       
              )
              
            )
            
  )
)

server <- (
  function(input,output){
    
    output$filterSelector <- renderUI({
      div(
        varSelectInput("filter_var", 
                       "Filter Variable:",
                       req(tableData())),
        selectizeInput("filter_vals",
                       "Filter Values:",
                       choices=NULL,
                       multiple = TRUE))
    })
    
    observe({
      
      fv <- req(input$filter_var)
      td <- req(tableData())
      updateSelectizeInput(inputId = "filter_vals",
                           choices = pull(td,fv))
    })
    col_min <- reactive({
      min = input$valore1
    })
    
    col_max <- reactive({
      max = input$valore2
    })
    tableData <- reactive({
      inFile <- input$file1
      
      if (!is.null(inFile)){
        read_excel(input$file1$datapath)
      } else {
        mtcars
      }
    })
    
    filteredTableData <- reactive({
      td <- req(tableData())
      fv <- req(input$filter_var)
      fc <- input$filter_vals
      if (isTruthy(fc)) {
        dplyr::filter(
          td,
          !!sym(fv) %in% fc
        )
      } else
        td
    })
    output$table1 = renderTable(filteredTableData())
    
    colonne <- reactive({ 
      database <- filteredTableData()
      data_size <- ncol(database)
      returnValue(data_size)
    })
    
    output$my_output_data <- renderText({colonne()})
    
    function(input, output) {
      output$result <- renderText({
        paste("You chose", input$state)
      })
    }
    
    
    output$my_output_data <- renderText({colonne()})
    ###correlation
    observeEvent(input$calculate_cor, {
      intervall <- col_min():col_max()
      df_data_cor<-filteredTableData()[intervall]
      df_data_cor_scale<-cor(df_data_cor)
      
      output$cor<-renderPlot({
        corrplot(df_data_cor_scale,
                 method = "pie")
      })
    })
  })  

shinyApp(ui,server)

I have this error:
Warning: Error in updateSelectInput

and the app doesn't work :thinking:

I tested the above... and confirmed it works in shiny 1.6
it doesnt work in shiny 1.5 without the following changes.

  1. extend the server function to have a session param
server <- (
  function(input,output,session){
  1. pass the session param to the updateSelectizeInput
      updateSelectizeInput(session = session,
                           inputId = "filter_vals",
                           choices = pull(td,fv))

Ok this problem is solved, but now when I browse my excel file I have this error:

Warning: Error in : Can't extract columns that don't exist.
x Column mpg doesn't exist.

I'm trying to solve it, but I can't find where is the error

   observe({
      fv <- as.character(req(input$filter_var))
      td <- req(tableData())
      if(! fv %in% names(td))
        return(NULL)
      updateSelectizeInput(inputId = "filter_vals",
                           choices = pull(td,fv))
    })

It works! Thank you very much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.