Reputation: 204
I am working on a feature which allows my markdown file to conditionally execute chunks based on a parameters sent from my shiny app. Some information about how this works here: https://shiny.rstudio.com/articles/generating-reports.html
Within the downloadhandler()
there is an argument which calls upon params =
which I give it a list, for example that list would look like this;
params <- list(report_name = input$J, data = data(), data2 = data2())
So my aim is to have an if else statement that would code data2 to be NULL
or NA
with the following; data2 = if( exists("data2") ) {data2()} else {NA}
This would allow me to stop some chunks in markdown from running by setting the eval='someconditionthatsfalse'
if data2()
does not exists or is empty in some way.
The issue I am running into is that this always exists.
Any help would be greatly appreciated.
A reprex to help with the problem.
library(shiny)
ui <- fluidPage(
actionButton("simulate", "go"),
textOutput("doesitexist")
)
server <- function(input, output, session) {
output$doesitexist <- renderText({
if( exists("data2") ) {print("yes it exists")} else {print("not it does not exist")}
})
data2 <- eventReactive(input$simulate, {
data.frame(x = 1)
})
}
shinyApp(ui, server)
Upvotes: 2
Views: 1629
Reputation: 12461
There are a couple of problems with your code. First, data2
is an observer of your button rather than the data.frame
whose existence you want to test. It will always exist within your server function, that's why it your test for existence always returns TRUE
. Second, because - however you’ve set things up - your reactive will always exist within the server function, exists
won't work. You need to use another condition and take an indirect approach. I've chosen to use reactiveValues
.
[You could also use reactiveValue
, but I prefer reactiveValues
even when I have only one reactive value to deal with because the syntax remains the same when moving from one reactive value to more than one.]
I set the reactive value to NA
to start with, and test for existence with is.na
.
Here's some working code:
library(shiny)
ui <- fluidPage(
actionButton("simulate", "Go"),
textOutput("doesitexist")
)
server <- function(input, output, session) {
v <- reactiveValues(data2=NA)
output$doesitexist <- renderText({
if (is.na(v$data2)) "No, it doesn't exist" else "Yes, it does exist"
})
observeEvent(input$simulate, { v$data2 <- data.frame(x=1)})
}
shinyApp(ui, server)
Upvotes: 3