Marco Loya
Marco Loya

Reputation: 43

In R shiny, how can I use data that I generated in an observeEvent (button click) outside of that observeEvent?

Say I do an observeEvent like this where I generate random numbers, and then another to export those numbers to a csv:

  observeEvent(input$generateButton, {
    u = runif(input$nNumericInput)
  })
  observeEvent(input$exportButton, {
    write.csv(data.frame(u),"randomNumbers.csv", row.names = FALSE)
  })

That's basically what I'm trying to do but I'm generating the numbers in a more complex way that I don't want to repeat for each button because of efficieny.

Upvotes: 2

Views: 842

Answers (1)

heds1
heds1

Reputation: 3438

Here's a working example. I'm also showing a table of the data that's produced when you update the numericInput. This should save in your working directory. Note that my_df is generated with an eventReactive, because it should be a reactive value (it should change when we change the numericInput), whereas write.csv is called within an observeEvent, because it's simply triggered by clicking the button (i.e., it's not creating any reactive object). Hope that helps.

library(shiny)

ui <- {
    fluidPage(
        fluidRow(
            numericInput(
                inputId = 'num_input',
                label = 'Input',
                value = 5),
            actionButton(
                inputId = 'num_input_button',
                label = 'Generate df'),
            actionButton(
                inputId = 'write_data',
                label = 'Write to csv')
        ),
        fluidRow(
            tableOutput('table')
        )
    )
}

server <- function(input, output, session) {

    my_df <- eventReactive(input$num_input_button, {
        runif(input$num_input)
    })

    observeEvent(input$write_data, {
        write.csv(my_df(), 'random_numbers.csv')
    })

    output$table <- renderTable({
        my_df()
    })

}

shinyApp(ui, server)

Upvotes: 1

Related Questions