In a shiny app, I check the validity of an input with req and update an output if the requirement on the input is TRUE (i.e. not empty, not FALSE, etc.).
I would like to run some code if the req is FALSE, i.e. use a req() else {}-like structure.
I could use an if() {} else {} conditional structure, but the req tests many things that I would prefer to avoid implementing myself.
Here is a MWE:
- If the input
text_inis valid, a reactive valuelocal$textis updated. - The content of the reactive value is then printed to the output
text_out. - When the input
text_inis not valid, I would like to execute some code, e.g.local$text <- "no text"
Note: I could run local$text <- "no text" before using the req but the app I am developing (not this example) uses multiple req and I cannot define a "default" value before calling these req.
library(shiny)
ui <- fluidPage(
textInput("text_in", label = "write", value = "default"),
verbatimTextOutput("text_out", placeholder = TRUE)
)
server <- function(input, output) {
local <- reactiveValues(text = NULL)
observe({
req(input$text_in)
local$text <- input$text_in
# else {
# local$text <- "no text"
# }
})
output$text_out <- renderText({
local$text
})
}
shinyApp(ui = ui, server = server)
Solution proposed by @mr-putter using shiny::isTruthy:
observe({
if(isTruthy(input$text_in)) {
local$text <- input$text_in
} else {
local$text <- "no text"
}
})