在Shiny教程中,有一个例子:
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() })
})
Run Code Online (Sandbox Code Playgroud)
我不知道如何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 })
})
Run Code Online (Sandbox Code Playgroud)
Ram*_*han 22
使用
currentFib <- reactiveValues({ fib(as.numeric(input$n)) })在这种情况下不起作用.您将收到一条错误消息,指出您正在访问"被动上下文"之外的被动值.
但是,如果将其包装在函数调用中,它将起作用:
currentFib <- function(){ fib(as.numeric(input$n)) }
这是有效的,因为现在函数调用在一个被动上下文中.
在关键的区别是他们让中区别闪亮的文档,无"源"与"导体".在那个术语中,reactive({...})是一个指挥,但reactiveValues只能是一个来源.
以下是我的想法reactiveValues- 作为一种扩展input在UI.R中指定的方法.有时候,插槽input是不够的,我们想要基于那些输入槽的派生值.换句话说,它是一种扩展input槽列表以供将来反应计算的方法.
Reactive()按照你说的做法 - 每当任何无效值发生变化时重新运行表达式后,它会返回值.如果您查看源代码,reactive您可以看到它:最后一行是正在返回的缓存值:Observable$new(fun, label)$getValue其中'fun'是在调用中发送的表达式reactive.
| 归档时间: |
|
| 查看次数: |
7444 次 |
| 最近记录: |