R shiny 变量每单击一次 actionButton 就会增加 1

R shiny variable increases by 1 each time actionButton is clicked

提问人:Subaru Spirit 提问时间:7/16/2021 更新时间:7/16/2021 访问量:1263

问:

我希望每次增加 actionButton 时变量 x 的值增加 1,例如,请参阅下面的可重现代码。但是,observeEvent 中的代码是隔离的,x 的值不会以增量方式更新。

library(shiny)

ui <- fluidPage(
  actionButton("plus","+1"),
  textOutput("value")
)

server <- function(input, output, session) {
  x = 1
  observeEvent(input$plus,{
    x = x+1
    output$value = renderText(x)
  })
}

shinyApp(ui, server)
r 闪亮

评论


答:

5赞 MrFlick 7/16/2021 #1

您需要确保要更改的值是响应式的。您可以通过使用 来使 reactive 。然后,当您想要调用的当前值以及想要更改 的值时,请使用xreactiveVal()xx()xx(<new value>)

library(shiny)

ui <- fluidPage(
  actionButton("plus","+1"),
  textOutput("value")
)

server <- function(input, output, session) {
  x = reactiveVal(0)
  observeEvent(input$plus,{
    x(x()+1) # increment x by 1
  })
  output$value = renderText(x())
}

shinyApp(ui, server)
2赞 TarJae 7/16/2021 #2

这是一个简单的计数器:请参阅此处:https://gist.github.com/aagarw30/69feeeb7e813788a753b71ef8c0877eb

library(shiny)

# Define UI for application
ui <- fluidPage(

    # Application title
    titlePanel("Counter"),


        # Show button and text
        mainPanel(
            actionButton("add1", "+ 1"),
            br(),
            textOutput("count")
        )
    )

# Define server logic required to draw a histogram
server <- function(input, output) {

    counter <- reactiveValues(countervalue = 0) # Defining & initializing the reactiveValues object
    
    observeEvent(input$add1, {
        counter$countervalue <- counter$countervalue + 1   # if  the add button is clicked, increment the value by 1 and update it
    })
    
    output$count <- renderText({
        paste("Counter Value is ", counter$countervalue)   # print the latest value stored in the reactiveValues object
    })
}

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