cycle through plots generated with function using slider

Solution 1:

There are a few ways you could do this. I think the most concise way I could think of is to use the get() command. This will let you find an object in your environment when called as a string (input$variable). The only new items are the reprex at the top and the server body. If I misunderstood the prompt, let me know and I'll try to update my answer.

library(shiny)
library(tidyverse)

# reprex ----
qc <- 
  mtcars |> 
  pivot_longer(everything()) |> 
  print()

s_75 <- function(var) ggplot(mtcars, aes(get(var))) + geom_bar() 
s_80 <- function(var) ggplot(mtcars, aes(get(var))) + geom_dotplot() 
s_85 <- function(var) ggplot(mtcars, aes(get(var))) + geom_histogram() 
s_90 <- function(var) ggplot(mtcars, aes(get(var), 1)) + geom_count() 
s_95 <- function(var) ggplot(mtcars, aes(get(var))) + geom_density() 


# ui ----
ui <- pageWithSidebar(
  # App title ----
  headerPanel("Set"),

  # Sidebar panel for inputs ----
  sidebarPanel( # Input: Selector for variable to plot against  ----
    selectInput("variable", "Name:", unique(qc$name)),
    sliderInput("quantile", "Quantile Range:",
      min = 75, max = 95, value = c(85), step = 5
    )
  ),
  # Main panel for displaying outputs ----
  mainPanel(
    h1("Header 1"),
    plotOutput("plot", width = "100%")
  )
)


# server ----
# Define server logic to plot various variables against 
server <- function(input, output, session) {
  fn <- reactive(get(paste0("s_", input$quantile)))
  output$plot <-  renderPlot(fn()(input$variable), height = 600, width = 800)
                          #    ^^^ note that the reactive value goes fn()(var)
}
  
shinyApp(ui, server)