这个问题与this one有关.两者可以生成相同的功能,但实现略有不同.一个显著的区别是reactiveValue
是一个可以有多个值的容器,比如input$
.在shiny documentation中,功能通常使用reactive()
实现,但在大多数情况下,我发现reactiveValues()
更方便.这里有trap 吗?这两者之间还有什么我可能不知道的重大区别吗?这两个代码段是等效的吗?
请参阅使用以下方法实现的相同example code:
-
react 性的表达:
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)
-
无功值:
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)