Hi there,
You can use the updateSelectInput function to change the choices of an input dynamically through the server. Here is an example
library(tidyverse)
library(shiny)
library(shinydashboard)
library(janitor)
library(gapminder)
library(ggthemes)
gapminder<-gapminder %>% clean_names()
#Get all the unique continents and their countries
countryNames = gapminder %>% select(continent, country) %>%
distinct() %>% arrange(country)
ui<-dashboardPage(
skin="red",
dashboardHeader(title="Life expectancy across continents",titleWidth = 500),
dashboardSidebar(selectInput("continent","Select the continent",choices = sort(unique(gapminder$continent)),multiple=T,selected="Asia"),
selectInput("country","Select the country",choices=c(),multiple=T)),
dashboardBody(
tabsetPanel(
type="tabs",
id="tab_selected",
tabPanel(title="Continent-view",
plotOutput("plot1")),
tabPanel(title="Country-view",
plotOutput("plot2"))
)
)
)
server<-function(input, output, session){
#Data per continent
continent<-reactive({
gapminder %>%
filter(continent %in% input$continent) %>%
group_by(continent,year) %>%
summarise(mean_exp=mean(life_exp),.groups = "drop")
})
#Data per country
countries<-reactive({
gapminder %>%
filter(country %in% input$country) %>%
group_by(country,year) %>%
summarise(mean_exp=mean(life_exp),.groups = "drop")
})
#Change country input optoins if continents change
observeEvent(input$continent, {
#Filter countries based on current continent selection
countriesToShow = countryNames %>%
filter(continent %in% input$continent) %>% pull(country)
#Update the actual input
updateSelectInput(session, "country", choices = countriesToShow,
selected = countriesToShow[1])
})
#Plot the continent data
output$plot1<-renderPlot({
ggplot(continent(),aes(year,mean_exp,color=continent))+
geom_line(size=1.5)+
theme_minimal()+
labs(title="How has life expectancy increased across different continents in the post-war period?",x="Year",y="Average Life Expectancy")
})
#Plot the country data
output$plot2<-renderPlot({
ggplot(countries(),aes(year,mean_exp,color=country))+
geom_line(size=1.5)+
theme_minimal()+
labs(title="How has life expectancy increased across different countries in the post-war period?",x="Year",y="Average Life Expectancy")
})
}
shinyApp(ui,server)
I also added a new tab with plot per country so you can see how it would work if you select different countries.
Hope this helps,
PJ