简体   繁体   中英

R Shiny: Defining a vector with two action buttons

im working on a shiny app. What i am trying to do: I want to "record" the cronological order of the activation of two different action buttons into a vector.

For example if button1 (red) is pressed twice, then button2 (black) is pressed once and then button1 (red) is pressed once again => The vector should look like: col = c("red","red","black","red").

What i did so far is this (in a lot of different variations):

col <- NULL observeEvent(input$rot, {col<-c(col,"red")}) observeEvent(input$schwarz, {col<-c(col,"black")}

input$rot und input$schwarz are the names of the action buttons. So i assumed the respective color should be added to the vector each time one of the buttons is pressed. BUT: Nothing happens... Of course i paste the vector col in the app, that is definitely not the problem.

It would be great if somebody has an idea. Thanks

You can use reactiveValues to store a vector col on the server side:

geschichte <- reactiveValues(col = NULL)

You can then access it within a reactive context via geschichte$col or via geschichte[["col"]] and simply overwrite as if geschichte was a regular list:

 observeEvent(input$rot, {
    geschichte$col <- c(geschichte$col, "red")
  })

Full example:

library(shiny)
rm(ui) ; rm(server)

ui <- fluidPage(
  actionButton("rot", "Red"),
  actionButton("schwarz", "Black"),
  br(),
  textOutput("col")
)

server <- function(input, output) { 

  geschichte <- reactiveValues(col = NULL)

  observeEvent(input$rot, {
    geschichte$col <- c(geschichte$col, "red")
  })

  observeEvent(input$schwarz, {
    geschichte$col <- c(geschichte$col, "black")
    })

  output$col <- renderText({
    geschichte$col
  })
}

shinyApp(ui, 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