问题
I would like to know how to prevent an event happened if no UI inputs are available. In the following example, there is an action button called Add UI
. The idea is the users can click that button and add a numeric input as many times as they want. They can then input numeric values. When they are ready, they can click the Sum
button. The total of these numbers would be the input value for the "Total" numeric input.
However, if the users click the Sum
button before adding any UIs, the app will stop. I would like to make the Sum
button clickable even there are no added UIs, keeping the input value of the "Total" numeric input to be 0
.
A relared question about how to calculate the sum of added UI inputs is from here: Refer to the Updated UI Input ID and Calculate the Sum in Shiny
library(shiny)
# Define UI
ui <- fluidPage(
actionButton("add", "Add UI"),
actionButton("sum", "Sum"),
# Input as the sum
numericInput(inputId = "Total", label = "Total", value = 0)
)
# Server logic
server <- function(input, output, session) {
observeEvent(input$add, {
insertUI(
selector = "#add",
where = "afterEnd",
ui = numericInput(paste0("txt", input$add), label = "Number", value = 0)
)
})
Num_In <- reactiveValues(
Total_In = 0
)
total_input <- reactive({Num_In$Total_In})
observeEvent(input$sum, {
num_names <- names(input)[grepl("^txt", names(input))]
Num_In$Total_In <- sum(sapply(num_names, function(x) input[[x]]), na.rm = TRUE)
updateNumericInput(session = session,
inputId = "Total",
value = total_input())
})
}
# Complete app with UI and server components
shinyApp(ui, server)
回答1:
Would a simple if
condition work? You can check if object num_names
length is equal to 0
:
if (length(num_names) == 0) {
foo <- 0
} else {
foo <- sum(sapply(num_names, function(x) input[[x]]), na.rm = TRUE)
}
This snippet checks if length is 0
and assigns 0
or uses sum
over num_names
.
Full observeEvent
code:
observeEvent(input$sum, {
num_names <- names(input)[grepl("^txt", names(input))]
if (length(num_names) == 0) {
foo <- 0
} else {
foo <- sum(sapply(num_names, function(x) input[[x]]), na.rm = TRUE)
}
Num_In$Total_In <- foo
updateNumericInput(session = session,
inputId = "Total",
value = total_input())
})
来源:https://stackoverflow.com/questions/55579248/prevent-an-event-happened-in-shiny-if-no-ui-inputs-are-available