R Shiny:对不同的输出控件重复使用冗长的计算

Pau*_*ers 5 r shiny

我在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]
    })
})
Run Code Online (Sandbox Code Playgroud)

helpers.R包含someLengthyComputation返回大小为3的向量的方法.如何在每次txtInput更改时调用它三次,并且在更新所有三个文本输出控件时只调用一次?

zer*_*323 5

你可以简单地someLengthyComputation放在一个reactive表达式中:

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

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

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

    output$txtOutput3 <- renderText({ 
        someExpensiveValue()[3]
    })
})
Run Code Online (Sandbox Code Playgroud)

someLengthyComputation只有在input$txtInput更改和第一个输出呈现时才会触发,否则someExpensiveValue将返回缓存值.

也有可能,但执行策略是有一点点不同,使用的组合reactiveValuesobserve.

如果someLengthyComputation真的很贵,你应该考虑添加一个动作按钮或一个提交按钮,并仅在点击它时触发计算,特别是当你使用时textInput.