Cactus
Cactus

Reputation: 924

RStudio and Shiny: define a reactiveValues with a Reactive

I am having a dataframe that is build depending on user input, choosing different filters. I then want to create a bar plot from this custom dataframe where the user can click on to exclude bars from the plot. I basically followed this example: https://gallery.shinyapps.io/106-plot-interaction-exclude/

However, when I try to define my reactiveValues value with my reactive, I can not define it and get an error. I am suspecting I can not define a reactiveValues with a reactive, is this right? How should I handle this then? Should I use reactives instead of reactiveValues?

Example code:

Server

server <- function(input, output) {
  df <- reactive({
  input$input1
})

vals2 <- reactive({
   (df())
})
output$Id1 <- renderText({
   vals2()
})

vals <- reactiveValues()
vals$bla <- df()
}

UI

library(shiny)
ui <- fluidPage(
  fluidRow(
  column(width= 4,
       textInput(inputId = "input1", label = "Select number of rows", value = "10")
),
   column(width = 12,
       verbatimTextOutput(outputId = "Id1"),
       verbatimTextOutput(outputId = "Id2")
  )
 )
)

Upvotes: 1

Views: 879

Answers (1)

Lespied
Lespied

Reputation: 342

Create your reactiveValues towards the beginning of your function and initialise is with a NULL

vals <- reactiveValues(bla = NULL)

You can then write to vals$bla from inside observeEvent, for instance when a button is pressed.

You can read from the reactiveValue, for instance to draw a plot in the form:

output$myPlot <- renderPlot( some function of values$bla )

EDIT updating to add my comment, create an observeEvent which watches your input1, when this changes it will execture the code within {} which will write to your reactiveValue.

observeEvent(input$input1, {
    vals$bla <- input$input1    
})

Upvotes: 2

Related Questions