Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a value inside of reactive() change, depending on an observeEvent() inside of that reactive()

Tags:

r

shiny

Here is the snippet, the question is: how do i make it so observeEvent() inside a reactive() will change the a value?

edit: the real question is, "is it possible without reactiveValues()?

ui <- fluidPage(
  actionButton("btn_change", "Change Values"),
  actionButton("btn_print","Print values")
)

server <- function(input, output) {
    a <- 1
    data <- reactive({
      observeEvent(input$btn_change, {
        a <- a + 1
      })
      a
    })

  observeEvent(input$btn_print, {
    print(paste("data = ", data()))
  })
}

shinyApp(ui, server)
like image 266
Claud H Avatar asked Jul 27 '17 18:07

Claud H


1 Answers

EDIT: you modified the question to ask if it is possible without reactiveValues. In this specific case, yes, because an actionbutton's value is incremented by 1 every time you click it. The previous answer with reactiveValues that is more widely applicable is shown at the bottom of this post.

library(shiny)
ui <- shinyUI(
  fluidPage(
    actionButton("btn_change", "Change Values"),
    actionButton("btn_print","Print values")
  )
)

server <- function(input, output) {
  a <- 1

  data <- reactive({
    a + input$btn_change 
  })

  observeEvent(input$btn_print, {
    print(paste("data = ", data()))
  })

}

shinyApp(ui, server)

EDIT. modified the solution based on your comments

I think what you are trying to do is increment the value of a reactive every time you click a button. You can achieve that by using a reactiveVal. You can get its value by doing x(), and set its value by x(1), where x is the name of the reactivevalue.

Note that you can use this reactiveval() in your reactive. Any time you click the button, the reactiveval will increase, and that will trigger the calculation of your reactive.

library(shiny)
ui <- shinyUI(
  fluidPage(
    actionButton("btn_change", "Change Values"),
    actionButton("btn_print","Print values")
  )
)

server <- function(input, output) {
  a <- 1

  data <- reactiveVal()
  data(a)

  observeEvent(input$btn_change, {
    old_value = data()
    data(old_value+1)
  })

  your_reactive <- reactive({
    data()*2+1
  })


  observeEvent(input$btn_print, {
    print(paste("data = ", your_reactive()))
  })

}

shinyApp(ui, server)
like image 126
Florian Avatar answered Nov 14 '22 22:11

Florian