我希望每次增加 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)
答案 0 :(得分:3)
您需要确保要更改的值是响应式的。您可以使用 x
使 reactiveVal()
具有反应性。然后,当您想要 x
的当前值时调用 x()
,当您想要更改 x
的值时,您使用 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)
答案 1 :(得分:1)
这是一个简单的计数器:参见此处: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)