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)