You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为purrr动态生成的输入使用shiny::req()函数?

解决动态生成输入的shiny::req()使用问题

你的动态输入ID是按{行号}_selectinput的格式生成的(比如1_selectinput、2_selectinput…),要确保所有这些输入都可用,可以按以下步骤操作:

步骤1:整理动态输入的ID列表

先把所有生成的输入ID整理成一个向量,方便后续批量处理:

input_ids <- paste0(1:number_tests, "_selectinput")

步骤2:在业务逻辑中批量调用req()

在需要用到这些动态输入的反应式表达式或输出里,用purrr结合req()批量检查所有输入是否已被正确赋值:

完整示例代码

# libraries
library(shiny)
library(magrittr)
library(dplyr)
library(purrr)
library(gt)
library(tibble)

# functions
selectizeInput_gt <- function(value, inputid, ...) {
  as.character(shiny::selectizeInput(paste0(value, inputid),
                                     ...)) %>%
    gt::html()
}

# datasets
number_tests <- 5
df <- data.frame("test_number" = 1:number_tests)

# 定义动态输入ID列表
input_ids <- paste0(1:number_tests, "_selectinput")

# UI
ui <- fluidPage(
  gt::gt_output(outputId = "table"),
  # 新增输出区域展示选择结果
  verbatimTextOutput("selected_values")
)

# server
server <- function(input, output, session) {
  output$table <- gt::render_gt({
    req(df)
    
    df %>%
      tibble::rownames_to_column() %>%
      dplyr::rowwise() %>%
      dplyr::mutate(
        rowname = as.numeric(rowname),
        selectinput_column = purrr::map(
          rowname,
          .f = ~ selectizeInput_gt(
            .x,
            "_selectinput",
            label = "",
            choices = c("A", "B", "C")
          )
        )
      ) %>%
      gt::gt()
    
  })
  
  # 示例:使用动态输入并通过req()确保所有输入可用
  output$selected_values <- renderPrint({
    # 检查所有动态输入都已选择有效内容
    req(purrr::map(input_ids, ~ input[[.x]]))
    
    # 获取并展示所有选择的值
    selected_vals <- purrr::map_chr(input_ids, ~ input[[.x]])
    names(selected_vals) <- input_ids
    selected_vals
  })
  
}

# runApp
shinyApp(ui, server) 

关键说明

  • req(purrr::map(input_ids, ~ input[[.x]]))会逐一验证每个输入ID对应的input值是否存在且不为空,只要有一个输入未选择,该反应式就会暂停执行,直到所有输入都满足要求。
  • 若只需确保部分输入可用,只需调整input_ids列表,保留需要检查的ID即可。

内容的提问来源于stack exchange,提问作者retlaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:55:20