【问题标题】:Why doesn't reactive({ }) take a dependency on a changing input?为什么 reactive({ }) 不依赖于不断变化的输入?
【发布时间】:2021-07-07 15:50:45
【问题描述】:

在下面的 Shiny 应用程序代码中,我希望在用户单击数据表中的新行时执行打印行。当我这样做时, textOutput 会按预期通过 input$table_rows_selected 更新所选行。但是为什么 change

我看到它可以与 observe({}) 一起使用,但最终我想使用一个在不同位置响应式返回的值(例如这里的 return 和 return2)。

library(shiny)
library(DT)

ui <- fluidPage(

     DT::DTOutput("table"),
     
     textOutput("selected"),
     
     textOutput("return"),
     
     textOutput("return2")

)

server <- function(input, output) {

    output$table <- DT::renderDataTable({
        data.frame(a = 1:3, b = 4:6)
    }, selection = 'single')
    
    
    output$selected <- renderText({
        input$table_rows_selected
    })
    
    change <- reactive({
        input$table_rows_selected
        print("it changed!")
        "return"
    })
    
    output$return <- renderText({
        isolate(change())
    })
    
    output$return2 <- renderText({
        paste0(isolate(change()), "_2")
    })
    
    
}

# Run the application 
shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny datatables


    【解决方案1】:

    您的代码有 2 个问题:

    • reactive 只是一个函数,因此它的返回值是reactive 中生成的最后一个值 -> 您需要将input$table_rows_selected 放在最后
    • isolate(change()) 表示reactives 不依赖input$table_rows_selected -> 删除isolate
    library(shiny)
    library(DT)
    
    ui <- fluidPage(
      
      DT::DTOutput("table"),
      
      textOutput("selected"),
      
      textOutput("return"),
      
      textOutput("return2")
      
    )
    
    server <- function(input, output) {
      
      output$table <- DT::renderDataTable({
        data.frame(a = 1:3, b = 4:6)
      }, selection = 'single')
      
      
      output$selected <- renderText({
        input$table_rows_selected
      })
      
      change <- reactive({
        print("it changed!")
        input$table_rows_selected
      })
      
      output$return <- renderText({
        change()
      })
      
      output$return2 <- renderText({
        paste0(change(), "_2")
      })
      
      
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 2023-03-06
      • 2017-01-23
      • 1970-01-01
      • 2021-02-24
      • 2023-01-25
      • 2018-07-04
      相关资源
      最近更新 更多