gpt4 book ai didi

r - 如何在 R Shiny 中围绕响应式(Reactive)表达式包装函数?

转载 作者:行者123 更新时间:2023-12-04 09:35:56 24 4
gpt4 key购买 nike

最小的工作示例

假设我想要一个自定义版本的 renderDataTable ,我将命名为 myRenderDataTable并通过环绕 renderDataTable 来工作:

library(shiny)
runApp(list(
ui = basicPage(
actionButton("button", "Increase input"),
tabsetPanel(
tabPanel("table1", shiny::dataTableOutput("table1")),
tabPanel("table2", shiny::dataTableOutput("table2")),
tabPanel("table3", shiny::dataTableOutput("table3"))
)
),
server = function(input, output) {
myRenderDataTable <- function(a) {
renderDataTable(
data.frame(x = a, y = a^2, z = a^3),
options = list(bPaginate = as.logical(a %% 2))
)
}
output$table1 <- myRenderDataTable(input$button)
output$table2 <- myRenderDataTable(input$button + 1)
output$table3 <- myRenderDataTable(input$button + 2)
}
))

问题

不幸的是, myRenderDataTable不像 renderDataTable 那样具有反应性.点击 Increase input按钮应该会导致表格值发生变化,但不会。

那么出了什么问题呢?

尝试:将调用传递给 reactive :

output$table1 <- reactive(myRenderDataTable(input$button)) ) 导致:
Error during wrapup: evaluation nested too deeply: infinite recursion / options(expressions=)?
Error : evaluation nested too deeply: infinite recursion / options(expressions=)?

尝试:将调用传递给 observe :

observe(output$table1 <- myRenderDataTable(input$button))对这个问题没有影响

最佳答案

问题是 input$button被“急切地”评估 - 即 input$button + 1第一次运行时评估为 2,然后不再更改。你可以让它每次评估input$button通过显式使其具有反应性来进行更改:

library(shiny)
runApp(list(
ui = basicPage(
actionButton("button", "Increase input"),
tabsetPanel(
tabPanel("table1", shiny::dataTableOutput("table1")),
tabPanel("table2", shiny::dataTableOutput("table2")),
tabPanel("table3", shiny::dataTableOutput("table3"))
)
),
server = function(input, output) {
myRenderDataTable <- function(a) {
renderDataTable(
data.frame(x = a(), y = a()^2, z = a()^3),
options = list(bPaginate = as.logical(a() %% 2))
)
}
output$table1 <- myRenderDataTable(reactive(input$button))
output$table2 <- myRenderDataTable(reactive(input$button + 1))
output$table3 <- myRenderDataTable(reactive(input$button + 2))
}
))

关于r - 如何在 R Shiny 中围绕响应式(Reactive)表达式包装函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23395390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com