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

Shiny框架下实现矩阵式动态输入组件的技术问询

Solution for Dynamic Matrix Layout of Input Widgets in Shiny

Got it, let's fix this so your input widgets arrange neatly in a matrix when multiple columns are selected! Here's the modified code that handles both single and multi-column scenarios perfectly:

library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel(title = "Adding input widgets horizontally and dynamically"),
  sidebarLayout(
    sidebarPanel(
      numericInput("rows", "Input No. of rows", value = 5, min = 1),
      br(),
      numericInput("col", "Input No of columns", value = 1, min = 1)
    ),
    mainPanel(uiOutput("plo"))
  )
))

server <- function(input, output){
  output$plo <- renderUI({
    total_inputs <- input$rows * input$col
    
    # Generate all input widgets with row/column-specific IDs and labels
    input_widgets <- lapply(1:total_inputs, function(i){
      row_num <- ceiling(i / input$col)
      col_num <- ((i - 1) %% input$col) + 1
      numericInput(
        inputId = paste0("range_", row_num, "_", col_num),
        label = paste0("Col ", col_num),
        value = row_num
      )
    })
    
    # Split widgets into row groups
    widget_rows <- split(input_widgets, ceiling(seq_along(input_widgets)/input$col))
    
    # Convert each row group into a fluidRow with evenly spaced columns
    lapply(widget_rows, function(row_widgets){
      fluidRow(
        lapply(row_widgets, function(widget){
          column(width = 12 / input$col, widget)
        })
      )
    })
  })
}

shinyApp(ui, server)

Key Changes Explained:

  • Unique, Meaningful IDs: We now use paste0("range_", row_num, "_", col_num) for input IDs, so you can easily reference specific row/column inputs later if needed.
  • Responsive Grid Layout:
    • Shiny uses a 12-column grid system, so we calculate each widget's column width as 12 / input$col—this ensures widgets always fill the row evenly, no matter how many columns you select.
    • We split the full list of widgets into groups (one group per row), then wrap each group in a fluidRow and each widget in a column to get the horizontal arrangement.
  • Intuitive Labels: Labels now show "Col 1", "Col 2", etc., to match the widget's column position, making the UI easier to follow.

This setup will adapt automatically: set columns to 1 and it behaves just like your original code; set it to 2, 3, or more, and widgets will snap into a clean matrix layout.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:44:51