1
votes

Following the answers given in this link R shiny selectInput: how to search group name/label , I created a Shiny app exemplified below:

EDIT Kindly note the SQLDF part stands for the MySQL querying in the actual platform. Thus I would generally want to pass the values of the input$Search *to a MySQL query.

  library(shiny)
  library(tidyverse)
  library(sqldf)
  library(DT)
  library(stringr)

       df <- data.frame(empName = c("Jon", "Bill", "Maria", "Dan", "Ken", "Fay"),
             empID = c("J111", "B222", "M333", "D444", "K555", "F666"),
             empAge = c(23, 41, 32, 28, 35, 38),
             empSalary = c(21000, 23400, 26800, 27200, 30500, 32000),
             empGroup = c("Employee", "Employee", "Manager", "Manager", "Director","Director")
   )


     df$empGroup <- as.factor(as.character(df$empGroup))

    x <- as.vector(levels(df$empGroup))

      groups <- function(x){
                      for(i in 1:length(x)){
                        if(i == 1){
                        savelist <-c()
                       newlist <- list(list(value = x[i], label=x[i]))
                       savelist <- c(savelist, newlist) 
                      }else{
                       newlist <- list(list(value = x[i], label=x[i]))
                           savelist <- c(savelist, newlist) 
                        }
                          }
                     return(savelist)
                       }



           shinyApp(

                  ui = fluidPage(  

                         selectizeInput('Search', NULL, NULL, multiple = TRUE, options = list(
                                       placeholder = 'Select name',
                            # predefine all option groups
                           optgroups = lapply(unique(df$empGroup), function(x){
                            list(value = as.character(x), label = as.character(x))
                             }),
  
           # what field to sort according to groupes defined in 'optgroups'
                 optgroupField = 'empGroup',
  
          # you can search the data based on these fields
               searchField = c('empName', 'empGroup', 'empID'),
  
         # the label that will be shown once value is selected
               labelField= 'empName',
  
         # (each item is a row in data), which requires 'value' column (created by cbind at server side)
              render = I("{
                     option: function(item, escape) {
                 return '<div>' + escape(item.empName) +'</div>';
                        }
                   }")
                 )),
             hr(),
       fluidRow(
            column(6, DT::dataTableOutput("table1")))
            ),

    server = function(input, output, session) {  

                 updateSelectizeInput(session, 'Search', choices = cbind(df, value = 
                                                                    seq_len(nrow(df))), 
                     server = TRUE)


         df1 <- reactive ({ 
              Selected <-df %>% filter(empName %in% input$Search)%>% select(empID)
                    SelectedID<-sapply(Selected, as.character)
                     N<-stringr::str_c(stringr::str_c("'", SelectedID, "'"), collapse = ',')
                    sqldf(paste0("SELECT  empAge, empSalary  
                   FROM df  WHERE  empID IN (",N,")"))
                    })     

      output$table1 = DT::renderDataTable({ 
                    req(input$Search)
               df1()}, options = list(dom = 't'))  
           })

The app throws a warning Warning in stri_c(..., sep = sep, collapse = collapse, ignore_null = TRUE) : argument is not an atomic vector; coercing

But if I don't group the selectizeInput choices it works as in the app below :

   library(shiny)
   library(tidyverse)
   library(sqldf)
   library(DT)
   library(stringr)

   df <- data.frame(empName = c("Jon", "Bill", "Maria", "Dan", "Ken", "Fay"),
             empID = c("J111", "B222", "M333", "D444", "K555", "F666"),
             empAge = c(23, 41, 32, 28, 35, 38),
             empSalary = c(21000, 23400, 26800, 27200, 30500, 32000)
   )


  shinyApp(

     ui = fluidPage(
               selectizeInput( "Search", label = p("Select name"), choices = NULL,
                options = list(  placeholder = 'Select name', maxOptions = 10,
                                 maxItems = 3,  searchConjunction = 'and' )),
               hr(),
                 fluidRow(
          column(6, DT::dataTableOutput("table1")))
               ),

         server = function(input, output, session) {

                    updateSelectizeInput(session,
                     "Search",
                     server = TRUE,
                     choices = df$`empName`)


          df1 <- reactive ({ 
                    Selected <-df %>% filter(empName %in% input$Search)%>% select(empID)
                     SelectedID<-sapply(Selected, as.character)
                    N<-stringr::str_c(stringr::str_c("'", SelectedID, "'"), collapse = ',')
                     sqldf(paste0("SELECT  empAge, empSalary  
                     FROM df  WHERE  empID IN (",N,")"))
                   })     

           output$table1 = DT::renderDataTable({ 
                     req(input$Search)
                     df1()}, options = list(dom = 't'))  
         })

How could I achieve the same output with the first scenario where there is grouping in the selectizeInput ?

1

1 Answers

2
votes

Does the following do what you're after?

library(shiny)
library(tidyverse)
library(DT)

df <- data.frame(
    empName = c("Jon", "Bill", "Maria", "Dan", "Ken", "Fay"),
    empID = c("J111", "B222", "M333", "D444", "K555", "F666"),
    empAge = c(23, 41, 32, 28, 35, 38),
    empSalary = c(21000, 23400, 26800, 27200, 30500, 32000),
    empGroup = c("Employee", "Employee", "Manager", "Manager", "Director","Director"))
df$empGroup <- as.factor(as.character(df$empGroup))

ui <- fluidPage(
    selectizeInput(
        inputId = 'Search',
        label = NULL,
        choices = NULL,
        multiple = TRUE,
        options = list(
            placeholder = 'Select name',
            # predefine all option groups
            optgroups = lapply(unique(df$empGroup), function(x) {
                list(value = as.character(x), label = as.character(x))
            }),
            # what field to sort according to groupes defined in 'optgroups'
            optgroupField = 'empGroup',
            # you can search the data based on these fields
            searchField = c('empName', 'empGroup', 'empID'),
            # the label that will be shown once value is selected
            labelField= 'empName',
            # (each item is a row in data), which requires 'value' column (created by cbind at server side)
             render = I("{
                    option: function(item, escape) {
                return '<div>' + escape(item.empName) +'</div>';
                       }
                  }")
        )
    ),
    hr(),
    fluidRow(
        column(6, DT::dataTableOutput("table1"))))

server <- function(input, output, session) {
    updateSelectizeInput(
        session = session,
        inputId = 'Search',
        choices = cbind(df, value = seq_len(nrow(df))),
        server = TRUE)

    df1 <- reactive({
        df %>%
            rowid_to_column("idx") %>%
            filter(idx %in% input$Search) %>%
            select(empAge, empSalary)
        })

    output$table1 = DT::renderDataTable({
        req(input$Search)
        df1()
    }, options = list(dom = 't'))
}

shinyApp(server = server, ui = ui)

enter image description here

PS.

I have cleaned up your code a bit, as I found it quite difficult to understand/digest what you were doing. For example, I didn't see the point of using both sqldf and tidyverse; if you already load the full tidyverse, you might as well do all data manipulations/filtering with dplyr (rather than add another dependency). On a minor note, stringr is automatically loaded when you load tidyverse so there's no need for an explicit library(stringr) call. I removed the lines where you defined x and group which you don't use in this minimal code example. I'd also recommend using consistent indentation and whitespace usage according to one of the popular & publicly available R style guides. That'll help (both you and others) with readability.


Update

To perform the reactive data filtering in sqldf you can replace the df1 <- reactive({}) block from above with

library(sqldf)

...

df1 <- reactive({
    data <- transform(df, idx = 1:nrow(df))
    sqldf(sprintf(
        "select empAge, empSalary from data where idx in (%s)",
        toString(input$Search)))
})