首页 > 解决方案 > 如何在 R Shiny 中更改数字输入框的位置

问题描述

这张照片是我尝试@Ben 的代码时发生的情况。现在,输入框框在另一个下方显示。我希望能够将它们显示在矩阵中,以便有input$numoc行和input$inp1列。

用户界面

numericInput("cols", "Enter number of columns:",min=1,1),
numericInput("rows", "Enter number of rows:",min=1,1)

服务器

output$matrixx <- renderUI({
    k= rep(c(1:input$rows), times = input$cols)
    mx<-max(input$rows,input$cols)
    lllist <- lapply(1:(input$cols*input$rows), function(i, j=((i-1)%/%input$rows)+1, y=k[[i]]) {
        iids <- paste("inp2", i, sep="")
        names<- paste("Treatment #",j," Outcome #",y,sep="")
        list(
            numericInput(iids,names, value=0, min=0, max=1, step=0.05)
        )
    })
    do.call(tagList, unlist(lllist, recursive = FALSE))
})

标签: ruser-interfaceinputshinynumeric-input

解决方案


当然,我们可以在我们的内部添加fluidRow和来实现这一点。columnrenderUI

这是一个最小的例子:

library(shiny)

ui <- fluidPage(
  
    numericInput("cols", "Enter number of columns:", min = 1, max = 4, 2), 
    numericInput("rows", "Enter number of rows:",    min = 1, 2),
    hr(),
    
    uiOutput("matrixx")
    
)

server <- function(input, output, session) {
  
    output$matrixx <- renderUI({
        
        ui_parts <- c()
        
        for(i in 1:input$rows){
            
            ui_parts[[i]] <- fluidRow(
                
                if(input$cols >= 1) {
                    column(3, 
                        textInput(
                            inputId = paste0("id", i + 10),
                            label   = paste0("id", i + 10) 
                        )
                    )
                },
                if(input$cols >= 2) {
                    column(3, 
                        textInput(
                            inputId = paste0("id", i + 20),
                            label   = paste0("id", i + 20) 
                        )
                    )
                },
                if(input$cols >= 3) {
                    column(3, 
                       textInput(
                           inputId = paste0("id", i + 30),
                           label   = paste0("id", i + 30) 
                       )
                    )
                },
                if(input$cols >= 4) {
                    column(3, 
                       textInput(
                           inputId = paste0("id", i + 40),
                           label   = paste0("id", i + 40) 
                       )
                    )
                }
            )
        }
        
        ui_parts

    })
    
}

shinyApp(ui, server)

为简单起见,我将其限制为 4 列,并以更重复但更易于阅读的格式编写。以额外的复杂性为代价,您可以使其与更多列一起使用,并通过使用额外的循环来缩短它。


推荐阅读