【问题标题】:In R shiny, how to generate sequential column headers for an input matrix?在 R 闪亮中,如何为输入矩阵生成顺序列标题?
【发布时间】:2021-11-21 11:28:51
【问题描述】:

运行以下 MWE 代码时,用户可以在输入矩阵网格中添加、删除或修改条目。根据这些用户输入生成一个简单的绘图。

您将看到输入矩阵的默认列标题 1 和 2。但是,当用户向矩阵添加数据时(只需单击空列并输入一个值),如何为该新列自动生成顺序列标题?因此,添加的第 3 列的标题标签将为 3,依此类推。删除列(通过单击当前出现在列标题字段中的“x”)将导致为剩余的列生成新的连续列编号。

请注意,通过将下面的 matrixInput 列 (col) 规范更改为 editableNames = TRUE,用户可以手动输入列标题。但是如果自动生成编号的标题并将editableNames 设置为 FALSE 会好得多。这些列标题编号将用于其他计算。

MWE 代码:

library(shiny) 
library(shinyMatrix) 

m <- matrix(runif(2), 1, 2, dimnames = list(c("Sample values"), c(1,2))) 

ui <- fluidPage(   
  titlePanel("Matrix inputs"),   
  sidebarPanel(     
    width = 6,     
    matrixInput(       
      "sample",       
      value = m,       
      rows = list(extend = FALSE),       
      cols = list(extend = TRUE, names = TRUE, editableNames = FALSE, delete = TRUE),
      class = "numeric"
      )   
    ),   
  mainPanel(     
    width = 6,     
    plotOutput("scatter")   
    ) 
  ) 

server <- function(input, output, session) {   
  
   output$scatter <- renderPlot({
     plot(1:ncol(input$sample),
          input$sample,
          xlab="Nbr of samples",
          ylab="Sample values"
          )
     }) 
   
   } 
shinyApp(ui, server) 

【问题讨论】:

    标签: r matrix shiny


    【解决方案1】:
    1. observe 服务器中输入矩阵的变化。
    2. 更改input$sample给出的矩阵的colnames。我在这里只是使用了连续的数字,但你可以提供任何你想要的算法。
    3. 使用updateMatrixInput 将新矩阵发送回 UI。请务必使用 isolate 以避免无休止的更改和刷新循环。
    library(shiny) 
    library(shinyMatrix) 
    
    initm <- matrix(runif(2), 1, 2, dimnames = list(c("Sample values"), c(1,2)))
    
    ui <- fluidPage(   
      titlePanel("Matrix inputs"),   
      sidebarPanel(     
        width = 6,     
        matrixInput(       
          "sample",       
          value = initm,       
          rows = list(extend = FALSE),       
          cols = list(extend = TRUE, names = TRUE, editableNames = FALSE, delete = TRUE),
          class = "numeric"
        )   
      ),   
      mainPanel(     
        width = 6,     
        plotOutput("scatter")   
      ) 
    ) 
    
    server <- function(input, output, session) {
      observe({
        mm <- input$sample
        colnames(mm) <- 1:ncol(mm)
        isolate(
          updateMatrixInput(session, "sample", mm)
        )
      })
      
      output$scatter <- renderPlot({
        plot(1:ncol(input$sample),
             input$sample,
             xlab="Nbr of samples",
             ylab="Sample values"
        )
      }) 
      
    } 
    shinyApp(ui, server) 
    

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2021-04-25
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      相关资源
      最近更新 更多