Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Shiny: Reuse lengthy computation for different output controls

Tags:

r

shiny

I have the following code in server.R:

library(shiny)

source("helpers.R")

shinyServer(function(input, output) {
    output$txtOutput1 <- renderText({ 
        someLengthyComputation(input$txtInput)[1]
    })
    output$txtOutput2 <- renderText({ 
        someLengthyComputation(input$txtInput)[2]
    })
    output$txtOutput3 <- renderText({ 
        someLengthyComputation(input$txtInput)[3]
    })
})

helpers.R contains the method someLengthyComputation which returns a vector of size 3. How can I get around calling it three times every time txtInput changes and only call it once while updating all three text output controls?

like image 332
Paul Reiners Avatar asked Aug 09 '15 18:08

Paul Reiners


1 Answers

You can simply place someLengthyComputation inside a reactive expression:

shinyServer(function(input, output) {
    someExpensiveValue <- reactive({
        someLengthyComputation(input$txtInput)
    })

    output$txtOutput1 <- renderText({ 
        someExpensiveValue()[1]
    })

    output$txtOutput2 <- renderText({ 
        someExpensiveValue()[2]
    })

    output$txtOutput3 <- renderText({ 
        someExpensiveValue()[3]
    })
})

someLengthyComputation will be triggered only when input$txtInput changes and the first of the outputs is rendered otherwise someExpensiveValue will return a cached value.

It is also possible, although execution strategy is a little bit different, to use a combination of reactiveValues and observe.

If someLengthyComputation is really expensive you should consider adding an action button or a submit button and triggering the computations only when it is clicked, especially when you use textInput.

like image 141
zero323 Avatar answered Sep 21 '22 00:09

zero323