r - 如果没有可用的 UI 输入,则防止在 Shiny 中发生事件

标签 r user-interface error-handling shiny shiny-reactivity

我想知道如果没有可用的 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/

相关文章:

python - 如何添加到导航pinax(0.9a2)的链接?

javascript - 要内联显示的 HTML 表单上的验证消息

r - 计算向量中超过 data.frame 列中的值的值的数量

r - dplyr::select 等效于对字符向量进行子集化

java - 如何远程控制 GUI 应用程序?

java - 将 jbutton 添加到 jtable 的更简单方法

php - PHP : Blank page, error reporting not functioning

r - R中的年度时间序列的decompose()

r - R 中的种子限制

c++ - 在硬件接口(interface)之间切换的最佳设计模式