Shiny selectInput interactive controls in R

Symbol of coding on a computer screen

How to use selectInput outputs

The key thing to note about using the output (result / choice) from a selectInput control is that the output HAS to be returned in a shiny reactive control, e.g. renderText(), renderPlot(), observeEvent() etc.

The selectInput output (result / choice) is called with the format input$inputID.

E.g. if our selectInput ID is “choose”, the selection control output is called using input$choose.

The selectInput outputs below work because they are wrapped in reactive functions, and will update when the input selection changes:

####---- inputID = "choose"
renderText({input$choose})

####---- inputID = "n_breaks"
renderPlot({
  hist(faithful$eruptions, probability = TRUE, breaks = 
    as.numeric(input$n_breaks),
    xlab = "Duration (minutes)", main = "Geyser eruption duration") ...

You can also create an output variable with renderText(), which you call elsewhere in the layout using textOutput():

# Create an output from the selectInput choice, named 'chosen2
 output$chosen2 <- renderText({input$choose})

# Use textOutput to place the output 'chosen2' in your layout
 textOutput("chosen2")

TheselectInput output below doesn’t work because it’s called directly by a ‘static’ function, which will not update if the selectInput control is refreshed:

# This is not in a reactive context so won't work
 chosen1 <- input$choose

## Error in .getReactiveEnvironment()$currentContext(): Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

Example selectInput code – input and output

---
title: "Shiny SelectInput"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(shiny)
```

```{r error=TRUE}

inputPanel(selectInput(inputID="choose", 
        label="Select", choices =c("Red","Green","Blue")),
	renderText({paste0("You chose: ",input$choose)}))

# use a reactive context to display the selectInput choice
# if wanted, we can also include this within the inputPanel above
 renderText({input$choose})

# This is not in a reactive context so won't work
chosen1 <- input$choose

# Create an output from the selectInput choice
  output$chosen2 <- renderText({input$choose})

# Use textOutput to place the output in your layout
  textOutput("chosen2")

# no input panel formatting
  selectInput("choose2",label="Select", choices =c("Red","Green","Blue"))

# input panel formatting with inputPanel()
  inputPanel(selectInput("choose", label="Select",choices 
          =c("Red","Green","Blue")))
```

Pages: 1 2 3