简体   繁体   中英

R shiny variable increases by 1 each time actionButton is clicked

I want the variable x's value to be increased by 1 each time the actionButton is increased, see below reproducible code for example. However the code inside observeEvent are isolated, and the value of x won't get updated incrementally.

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)

You need to make sure the value you want to change is reactive. You can make x reactive by using reactiveVal() . Then when you want the current value of x you call x() and when you want to change the value of x , you use x(<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)

This is a simple counter: See here: 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM