Shiny: let you choose the reactivity of your choice

I am creating an application with several tabs, some of which are related to excessive calculations and others that are quickly calculated. An ideal flag might be that allows the user to choose between reactivity or manual update in combination with the Refresh button.

The simple example below illustrates what I am aiming for. It almost works, except for one final update when the “Automatic update” -checkbox box is not checked, which is a pain if the computational intensive tab should be opened. Is there any way around this?

ui.r

library(shiny) shinyUI(fluidPage( titlePanel("Test"), sidebarLayout( sidebarPanel( checkboxInput("autoRefresh", "Automatically refresh", TRUE), actionButton("refresh", "Refresh!"), radioButtons("choice", "Choice of value:", c("10" = 10, "20" = 20)) ), mainPanel( tabsetPanel(type = "tabs", tabPanel("Add random decimals to value", textOutput("value")) ) ) ) )) 

server.r

 library(shiny) shinyServer(function(input, output) { output$value <- renderText({ input$refresh if(input$autoRefresh == 1) { input$choice } isolate({ output <- runif(1,0,1) + as.numeric(input$choice) }) }) }) 

Thank you very much in advance!

+6
source share
2 answers

In this decision, I made two observers: one when the refresh button is pressed, and the second when changing the choice . The first always updates the output.

The second checks the status of input$autoRefresh , and then either simply issues or updates renderText .

Unfortunately, you must have the runif command written twice, which may be bad for updating your code (it is easier to enter errors if you do something twice). In practice, you may need to create a new function, and then simply call this function if it is a complex / multi-line process in your real application.

  shinyServer(function(input, output) { observe({ input$refresh output$value<-renderText({ isolate(runif(1,0,1) + as.numeric(input$choice)) }) }) observe({ input$choice output$value<-if(input$autoRefresh==0) return() else { renderText({isolate(runif(1,0,1) + as.numeric(input$choice))}) } }) }) 
+2
source

You can cache output and shortcut - return it when necessary

 library(shiny) shinyServer(function(input, output) { output$value <- renderText({ input$refresh if(input$autoRefresh == 1) { input$choice } else return(cachedOutput) isolate({ cachedOutput <<- output <- runif(1,0,1) + as.numeric(input$choice) }) }) }) 
+2
source

Source: https://habr.com/ru/post/981012/


All Articles