reactiveValue
是一个容器,可以有多个值,像input$
一样。在shiny文档中,通常使用reactive()
来实现功能,但在大多数情况下,我发现reactiveValues()
更方便。这里有什么要注意的吗?这两者之间还有其他重大差异我可能不知道的吗?这两个代码片段是否等效?请查看使用以下方式实施的示例代码。
a reactive expression:
library(shiny) ui <- fluidPage( shiny::numericInput(inputId = 'n',label = 'n',value = 2), shiny::textOutput('nthValue'), shiny::textOutput('nthValueInv') ) fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2)) server<-shinyServer(function(input, output, session) { currentFib <- reactive({ fib(as.numeric(input$n)) }) output$nthValue <- renderText({ currentFib() }) output$nthValueInv <- renderText({ 1 / currentFib() }) }) shinyApp(ui = ui, server = server)
a reactive value:
library(shiny) ui <- fluidPage( shiny::numericInput(inputId = 'n',label = 'n',value = 2), shiny::textOutput('nthValue'), shiny::textOutput('nthValueInv') ) fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2)) server<-shinyServer(function(input, output, session) { myReactives <- reactiveValues() observe( myReactives$currentFib <- fib(as.numeric(input$n)) ) output$nthValue <- renderText({ myReactives$currentFib }) output$nthValueInv <- renderText({ 1 / myReactives$currentFib }) }) shinyApp(ui = ui, server = server)