Here I'm using 'mtcars' and will like to update my selectInputs based on the unique values in some column. First, we choose the type of engine and subset the data. Then we choose the cylinder but based on the remaining cylinder options in the subsetted data, and so forth. Last, we print the names of the cars. Code, which is not working, is as below:
library(shiny)
df <- mtcars
ui <- fluidPage(
sidebarPanel(
selectInput("engine", "Select engine:", choices = unique(df$vs)),
selectInput("cylinder", "Select cylinder:", choices = ""),
selectInput("gear", "Select gear:", choices = ""),
),
mainPanel(
textOutput("results")
)
)
server <- function(input, output, session) {
data <- reactiveValues()
observeEvent(input$engine, {
tmp <- df
tmp1 <- tmp[tmp$vs == as.numeric(input$engine),]
updateSelectInput(session, "cylinder", choices = unique(tmp1$cyl))
data()$tmp1 <- tmp1
})
observeEvent(input$cylinder,{
tmp1 <- data()$tmp1
tmp2 <- tmp1[tmp1$cyl == as.numeric(input$cylinder),]
updateSelectInput(session, "gear", choices = unique(tmp2$gear))
data()$tmp2 <- tmp2
})
observeEvent(input$gear,{
tmp2 <- data()$tmp2
tmp3 <- tmp2[tmp2$gear == as.numeric(input$gear),]
data()$tmp3 <- tmp3
})
output$results <- renderText({
print(row.names(data()$tmp3))
})
}
shinyApp(ui = ui, server = server)
CodePudding user response:
The issue is that you try to access your reactiveValues
data
using data()
. Instead, to set or get a value use e.g. data$tmp1
without parentheses. See ?reactiveValues
.
library(shiny)
df <- mtcars
ui <- fluidPage(
sidebarPanel(
selectInput("engine", "Select engine:", choices = unique(df$vs)),
selectInput("cylinder", "Select cylinder:", choices = ""),
selectInput("gear", "Select gear:", choices = ""),
),
mainPanel(
textOutput("results")
)
)
server <- function(input, output, session) {
data <- reactiveValues()
observeEvent(input$engine, {
tmp <- df
tmp1 <- tmp[tmp$vs == input$engine, ]
updateSelectInput(session, "cylinder", choices = unique(tmp1$cyl))
data$tmp1 <- tmp1
})
observeEvent(input$cylinder, {
tmp1 <- data$tmp1
tmp2 <- tmp1[tmp1$cyl == input$cylinder, ]
updateSelectInput(session, "gear", choices = unique(tmp2$gear))
data$tmp2 <- tmp2
})
observeEvent(input$gear, {
tmp2 <- data$tmp2
tmp3 <- tmp2[tmp2$gear == input$gear, ]
data$tmp3 <- tmp3
})
output$results <- renderText({
print(row.names(data$tmp3))
})
}
shinyApp(ui = ui, server = server)
#>
#> Listening on http://127.0.0.1:5721
#> character(0)
#> [1] "Mazda RX4" "Mazda RX4 Wag"