Peter Ohaver
Peter Ohaver

Reputation: 87

How to feed the output of one R Shiny input to another

I'm trying to figure out how to pass one Shiny input's value to another. My goal is to have a slider's value default to the value that corresponds to a selection from a dropdown above it. That is, I'm hoping that there's a way to pass the choice from selectInput() (essentially input$Character) to the value argument in sliderInput(). I want to try something like the below code, but it is an utter failure.

library(shiny)

ui <- fluidPage(
  sidebarPanel(
    selectInput(inputId="Character", label="Choose Your Character",
                             choices=starwars$name),
    sel = starwars %>% filter(name==input$name) %>% select(height),
    sliderInput(inputId="height", label="Choose character height ", min=0, 
                max=max(starwars$height), value=sel)
  ),
  mainPanel(
    verbatimTextOutput('text')
    )
)

server <- fuction(input, output) {
  output$text <- renderPrint({
    print(input$height)
    })
}

shinyApp(ui=ui, server=server)

Thanks!

Upvotes: 1

Views: 1073

Answers (1)

heds1
heds1

Reputation: 3438

Don't be afraid of using server-side processing, it's pretty straightforward!

library(shiny)

ui <- {
    fluidPage(
        selectInput("character",
            "Choose your character",
            choices = starwars$name
        ),
        uiOutput("height_ui"),
        verbatimTextOutput('text')
    )
}

server <- function(input, output, session) {
    
    output$height_ui <- renderUI({

        selected_character_height <- starwars %>%
            filter(name == input$character) %>%
            pull(height)

        sliderInput("height",
            "Choose character height ",
            min = 0L, 
            max = max(starwars$height, na.rm = TRUE),
            value = selected_character_height
        )
    })
    
    output$text <- renderPrint({
        print(input$height)
    })
}

shinyApp(ui, server)

Upvotes: 2

Related Questions