我想知道如果没有可用的 UI 输入,如何防止事件发生。在以下示例中,有一个名为 Add UI
的操作按钮。这个想法是用户可以单击该按钮并根据需要多次添加数字输入。然后他们可以输入数值。准备好后,他们可以单击 Sum
按钮。这些数字的总和将是“总计”数字输入的输入值。
但是,如果用户在添加任何 UI 之前单击 Sum
按钮,应用程序将停止。我希望即使没有添加 UI,Sum
按钮也可单击,并将“Total”数字输入的输入值保持为 0
。
有关如何计算添加的 UI 输入总和的相关问题来自此处: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)
最佳答案
简单的 if
条件有效吗?您可以检查对象 num_names
长度是否等于 0
:
if (length(num_names) == 0) {
foo <- 0
} else {
foo <- sum(sapply(num_names, function(x) input[[x]]), na.rm = TRUE)
}
此代码段检查长度是否为 0
并分配 0
或在 num_names
上使用 sum
。
完整的observeEvent
代码:
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())
})
关于r - 如果没有可用的 UI 输入,则防止在 Shiny 中发生事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579248/