I am having trouble with a Shiny app allowing dynamic changes in the display for one input (selectInput
) based on the value of a second input (radioButtons
). To clarify, I wrote a simplified version of my app relying on the Palmer penguins data producing the same error. I would like users to select multiple species from the data set, using either the scientific name or common name (selected with a radio button), for graphical summary. As far as I can tell, it looks like the species names are correctly updated using observeEvent
and updateSelectInput
, but the subsequent data selection isn't happening properly for some reason. When I try to plot the data, I receive the following error: ! Column scientificName
not found in .data
.
I would appreciate any insights about the error and strategies to fix it!
library(bslib)
library(palmerpenguins)
library(shiny)
library(tidyverse)
data(penguins)
penguins <- penguins |>
rename(commonName=species) |>
mutate(scientificName=factor(c(rep("Pygoscelis adeliae",152),rep("Pygoscelis papua",124),rep("Pygoscelis antarcticus",68))))
ui <- page_sidebar(
title = "Penguins Reprex",
sidebar = sidebar(selectInput('species','Choose species',choices=unique(penguins$scientificName),
selected=first(unique(penguins$scientificName)),multiple=TRUE),
radioButtons('name','Choose name display',choiceNames=c("Scientific name","Common name"),
choiceValues=c("scientificName","commonName"))),
plotOutput("plot",width="100%")
)
server <- function(input, output, session) {
data <- reactive({
penguins |>
filter(input$name %in% input$species) |>
group_by(input$name,year) |>
summarize(n = n())
})
output$plot <- renderPlot(
ggplot(data(), aes(x=.data[[input$name]],y=n,fill=year)) +
geom_bar(position="stack",stat="identity",width=0.7) +
xlab("Species") + ylab("Observations") +
theme_nice() +
theme(axis.text.x = element_text(angle=45,vjust=1,hjust=1)) +
scale_fill_custom() +
guides(fill=guide_legend(title="Years"))
)
observeEvent(input$name,{ updateSelectInput(session,'species','Choose species',choices=unique(penguins[[input$name]]),
selected=first(unique(penguins[[input$name]]))) },
ignoreInit=TRUE)
}
shinyApp(ui,server)