2013-08-19 65 views
15

Shiny tutorial,有一个例子:反应性值与反应性表达式有什么区别?

fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2)) 

shinyServer(function(input, output) { 
    currentFib   <- reactive({ fib(as.numeric(input$n)) }) 

    output$nthValue <- renderText({ currentFib() }) 
    output$nthValueInv <- renderText({ 1/currentFib() }) 
}) 

我不明白怎么reactive缓存值。它是否在内部执行类似return(function() cachedValue)的操作? 现在我想知道我能否做到这一点?

fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2)) 

shinyServer(function(input, output) { 
    currentFib   <- reactiveValues({ fib(as.numeric(input$n)) }) 

    output$nthValue <- renderText({ currentFib }) 
    output$nthValueInv <- renderText({ 1/currentFib }) 
}) 

回答

20

使用 currentFib <- reactiveValues({ fib(as.numeric(input$n)) })不会在这方面的工作。 您将收到一条错误消息,说您正在访问“被动环境”以外的被动值。

但是,如果你把它包装一个函数调用,而不是里面,它会工作:

currentFib <- function(){ fib(as.numeric(input$n)) }

这工作,因为现在的函数调用是一种反应性上下文中。

关键区别是它们在Shiny documentation中在被动“源”和“导体”之间所作的区别。在该术语中,reactive({...})导体,但reactiveValues只能是

  • 这是我怎么想的reactiveValues - 作为一种扩展input其获取UI.R.规定有时候,input中的插槽是不够的,我们希望根据这些输入插槽导出值。换句话说,这是一种扩展input时隙列表以用于将来的反应计算的方法。

  • Reactive()按照你所说的 - 每次任何被动值改变时重新运行表达式后返回值如果你看一下源代码reactive你可以看到它: 最后一行是正被返回缓存值:Observable$new(fun, label)$getValue其中“有趣”的是,在呼叫发送到reactive.

表达
相关问题