0

I am using shiny Rmarkdown document and I want to use a reactive data frame created in one chunk in a subsequent chunks. When I try to use the reactive data in chunk 2, which was created in chunk 1, I am getting error about using reactive without context. How do I fix it?

Operation not allowed without an active reactive context.* You tried to do something that can only be done from inside a reactive consumer.

Chunk1

sidebarPanel(
      shiny::radioButtons(
        inputId = "TrainingDataSource",
        label =  "Upload new training data or use default",
        choices =  c("Use existing" = "existing",
          "Upload new" = "new")
      )
    mainPanel(
      downloadButton("trainData_download", "Download Training Data (Phase I)")
    )



train.data <- reactive({
        if (input$TrainingDataSource == "existing") {
          df <- data.frame(x=rnorm(n),y=rnorm(n))
          
        } else {
          file = input$file1
          ext = tools::file_ext(file$datapath)
          
          # req(file)
          shiny::validate(need(ext == "csv", "Please upload a csv file"))
          read.csv(file$datapath, header = input$header) %>% as.data.frame() %>% drop_na
          
        }
      })


 trainData_download <- downloadHandler(
        filename = "data.csv",
        content = function(file) {
          write.csv(train.data(), file, row.names = FALSE)
        }
      )

Chunk 2

 tdf <- train.data()
head(tdf)
ok1more
  • 659
  • 6
  • 13
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. What exactly does the raw markdown of your document look like (including the YAML header)? – MrFlick Nov 03 '21 at 03:32

0 Answers0