Home > Software engineering >  Two observe events in shiny
Two observe events in shiny

Time:11-26

In shiny, I am trying to have two observe events at once. One of them is a URL passed parameter. The other is that what I press a "Run" button, I output a csv.

The first part works fine and can be verified by adding /?param=some_text. However when I press the "Run" button no csv is created. What am I missing here? I feel like I have actionButton setup up correctly and that observeEvent is the right command to put to the csv?

library(shiny)

ui <- fluidPage(
  textOutput("param"),
  actionButton(inputId = "button", label="Run")
)

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

  observe({
    query <- parseQueryString(session$clientData$url_search)
    if (!is.null(query[['param']])) {
      output$param <- renderText({
        query[['param']]
      })
    } else {
      output$param <- renderText({"unset"})
    }
  })

  observeEvent(input$button, {
    write.csv(iris, file = "temp.csv", row.names = TRUE)
  })
}

shinyApp(ui, server)

CodePudding user response:

I think the issue is with the filename which you're writing.

Listening on http://127.0.0.1:4380 Warning in file(file, ifelse(append, "a", "w")) : cannot open file '2022-11-25_10:32:31_temp.csv': Invalid argument Warning: Error in file: cannot open the connection

You can use gsub to parse the filename so its compatible or change it to something else:

  observeEvent(input$button, {
    myfile <- paste0(Sys.time(),"_temp.csv")
    myfile <- gsub(" ","_",myfile)
    myfile <- gsub("-","_",myfile)
    myfile <- gsub(":","",myfile)
    write.csv(iris, file = myfile, row.names = TRUE)
  })
  • Related