The reactive and isolate functions

If you need to call an input argument inside many output objects, you must create a reactive expression using the reactive function. Let's see an example:

library(shiny)

#the UI object
ui <- fluidPage(numericInput(inputId = "number",
label = "A number between 1 and 50:",
value = 1, min = 1, max = 50, step = 1),
textInput(inputId = "text", label = "A text box",
value = ""),
tableOutput(outputId = "table_a"),
tableOutput(outputId = "table_b"))

#the server function
server <- function(input, output) {
the_number <- reactive({input$number})
output$table_a <- renderTable(list(input$text, the_number()))
output$table_b <- renderTable(list(the_number(),
isolate({input$text})))
}

#Run the app
shinyApp (ui = ui, server = server)

This simple app creates a web page with two inputs and two tables. The first input is the numeric input as we used before, the second input is a textbox where the user can write any text. Both the number and the text are presented in table_a and table_b but in different orders. Note we used the reactive function to create a reactive expression called the_number; every time that we needed to use the expression inside the the_number object instead of calling input$number, we just called it as the_number() (you need to add the parentheses because the_number is an expression and not a variable). We called it twice, in the output$table_a object and in the output$table_b object. If you want to create a kind of list of reactive values, use the reactiveValues() function; it works similarly to the reactive function. Check the R documentation to see more about it (?reactiveValues).

If you pay close attention to the second output object, you'll see that we used the isolate function with the input$text object. If you run the code and try to insert a text in the textbox, you'll note that in the first table the text is actualized as soon as possible, whereas it is only actualized in the second table when you change the value in the numeric box. That is what the isolation function does: it saves the new interaction made by the user but doesn't call the server function to re-evaluate the code. It waits for another kind of interaction to trigger it, and when the server function is triggered and creates a new output, it pulls the newest value inside the isolated input element, and the output element is created with all of the values actualized. In our second table example, it happens when we change the numeric value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.14.200