rocknRrr
rocknRrr

Reputation: 421

Shiny with three inputs of selecting variable, its levels and adding other columns

From the code, renderUI in server is disconnected to the main variable selection, so as print textOutput() to main pannel.

I'm trying to build a shiny app has three inputs at the sidebar of

  1. selecting a main variable
  2. the levels of the selected main variable to choose(multiple)
  3. options of adding columns, and then print selected data at the main panel

for example, with iris,

  1. I choose Species
  2. level should show options of "setosa" "versicolor" "virginica" but which is not showing
  3. I can add other columns But the selected rows and columns are not printed at the main panel
data <- iris


ui <- fluidPage(
  
  titlePanel("Data selection"),
  sidebarLayout(
    sidebarPanel(
      selectizeInput("show_vars", "Main column:",
                     choices = colnames(data), multiple = FALSE),
      uiOutput("category1"),
      selectInput("add_col", "Add columns to display", names(data), multiple = TRUE)
    ),
    mainPanel(
      textOutput("selected")
    )
  )
)

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

  output$category1 <- renderUI({
    selectizeInput('cat1', 'Levels from main column', choices = levels(input$show_vars), multiple = TRUE)
  })
  
  
  df_subset <- eventReactive(input$cat1,{
    columns = names(data)
    if(input$cat1=="All") {df_subset <- data}
    else{df_subset <- data[data$Category1 == input$cat1, columns]}
  })
  
  output$selected <- renderText({ df_subset() })
}


shinyApp(ui, server)

Upvotes: 1

Views: 534

Answers (1)

YBS
YBS

Reputation: 21349

Perhaps you are looking for this

data <- iris


ui <- fluidPage(
  
  titlePanel("Data selection"),
  sidebarLayout(
    sidebarPanel(
      selectInput("show_vars", "Main column:",
                     choices = colnames(data), multiple = FALSE),
      uiOutput("category1"),
      selectInput("add_col", "Add columns to display", names(data), multiple = TRUE)
    ),
    mainPanel(
      DTOutput("selected")
    )
  )
)

server <- function(input, output,session) {
  
  output$category1 <- renderUI({
    req(input$show_vars)
    selectInput('cat1', 'Levels from main column', choices = c('All',levels(data[,input$show_vars])), multiple = TRUE)
  })
  
  
  df_subset <- reactive({
    req(input$cat1,input$add_col)
    columns <-  names(data) %in% input$add_col
    if(input$cat1=="All") {dfsubset <- data[,columns]}
    else {dfsubset <- data[data[,input$show_vars] == input$cat1, columns]}
    dfsubset <- as.data.frame(dfsubset)
  })
  
  output$selected <- renderDT({ df_subset() })
}

shinyApp(ui, server)

output

Upvotes: 3

Related Questions