gpt4 book ai didi

r - 操作按钮和observeEvent

转载 作者:行者123 更新时间:2023-12-02 02:50:13 26 4
gpt4 key购买 nike

我想要一个按钮来触发对预先指定的非 react 变量的操作 x 。每次按下按钮 x <- x + 1应予执行。为了检查是否正确完成,应显示结果。为了实现这一目标,我尝试了 observeEvent() 。但它只做了一次它应该做的事情。它如何正常工作?

看来rv仅在observeEvent()内可用功能。如果output$text_2 <- renderText({ rv$a })放置在 observeEvent() 之外发生错误。我如何使用 observeEvent() 内完成的内容外面?

library(shiny)
x <- 0

ui <- fluidPage(

actionButton(inputId = "action",
label = "action"),
textOutput("text_1"),
textOutput("text_2")

)

server <- function(input, output) {

output$text_1<- renderText({ input$action })

observeEvent(input$action, {
x <- x + 1
rv <- reactiveValues(a = x)
output$text_2 <- renderText({ rv$a })
})
}

shinyApp(ui = ui, server = server)

最佳答案

Daattalis 的答案很准确,但我想我可以发布一些示例来说明如何使用 Shinys react 值来做到这一点。

library(shiny)

ui <- fluidPage(

actionButton(inputId = "action",
label = "action"),
textOutput("txt_example1"),
textOutput("txt_example2"),
textOutput("txt_example3")

)

server <- function(input, output) {

# ------------------ Example 1 ------------------
# Use a list of reactive values
rv <- reactiveValues(x=0)

# Will update text output when rv$x is updated
observe({
output$txt_example1 <- renderText({ rv$x })
})


# ------------------ Example 2 ------------------
# Make variable a reactive
x <- 0
makeReactiveBinding('x')

# The only 'trick' here is that x is made a reactive so that the observer is
# triggered every time x is updated.
# If x is not made a reactive the value of x will still be updated but the observer
# wont trigger (see example 3).

observe({
output$txt_example2 <- renderText({ x })
})

# ------------------ Example 3 ------------------
# Use ordinary R scoping

x2 <- 0

printUpdate <- function(){
output$txt_example3 <- renderText({ x2 })
}

printUpdate() # Print first value

# onClick listener, same for all examples
observeEvent(input$action, {
rv$x <- rv$x + 1 # Example 1, update reactive list
x <<- x + 1 # Example 2, Save x to parent enviroment

# Example 3
x2 <<- x2 + 1 # Again, save x2 to parent enviroment, see help('<<-')
printUpdate() # Update textOutput
})


}

shinyApp(ui = ui, server = server)

希望这有帮助!

关于r - 操作按钮和observeEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671011/

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