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

如何从基于用户输入迭代创建的Shiny模块中获取值?

解决Shiny模块迭代调用server获取颜色并生成命名向量的问题

要实现迭代调用mod_fill_def_server()并将结果组合成符合ggplot2要求的命名向量,可以按照以下方式修改server部分:

完整server代码

server <- function(input, output, session) {
  vec <- reactive({
    switch(input$items, Animals = Animals, Vehicles = Vehicles)
  })
  
  output$levels_fills <- renderUI(
    purrr::map2(vec(), seq_along(vec()), function(level, n) {
      mod_fill_def_ui(glue("fill_{level}"), level, length(vec()), n)
    })
  )
  
  # 迭代调用模块server,收集每个颜色的响应式对象
  color_reactives <- reactive({
    purrr::map(vec(), function(level) {
      mod_fill_def_server(glue("fill_{level}"))
    })
  })
  
  # 组合成命名向量
  fill_colors <- reactive({
    # 获取每个颜色的当前值
    color_values <- purrr::map_chr(color_reactives(), ~.x())
    # 以选项名称为向量命名
    names(color_values) <- vec()
    color_values
  })
  
  # 输出测试结果
  output$fill_hex <- renderPrint({
    fill_colors()
  })
}

关键逻辑说明

  • 迭代调用模块server:用reactive()包裹purrr::map,确保每次切换选项(vec()更新)时,都会重新创建对应数量的模块server实例,和UI端的颜色选择器一一对应。
  • 生成命名向量:在fill_colors响应式对象中,遍历所有颜色的响应式实例获取当前选中的HEX值,再将vec()中的选项名作为向量的名称,最终得到c("Cat" = "#xxxxxx", "Dog" = "#yyyyyy")的格式,可直接传入ggplot2::scale_*_manual(values = fill_colors())使用。
  • 响应式同步:整个流程完全响应式,切换选项时UI和server端的模块实例、颜色向量会同步更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:39:24