Home > Mobile >  R shiny matrixinput with editable number of rows and columns
R shiny matrixinput with editable number of rows and columns

Time:12-14

I have this sort of "code" which inherently does not work as I cannot find a guide I can follow about matrixinput and rshiny on its own. Essentially, what I am hoping to create is a matrix input whose number of rows and columns can be changed through numeric inputs. How should I go about this?

library("shiny")
library("shinyMatrix")

textInput("rows", "Number of rows:", "")
textInput("columns", "Number of columns:", "")

ui <- fluidPage(
  titlePanel("shinyMatrix: Simple App"),
  sidebarPanel(
    width = 6,
    numericInput("rows", "Number of rows:", ""),
    numericInput("columns", "Number of columns:", ""),
  ),
  
  mainPanel(
    matrixInput("matrix1",
      value = m,
      rows = list(
        names = TRUE,
        editableNames = TRUE),
      cols = list (
        names = TRUE,
        editableNames = TRUE
      ),
      class = "numeric"),
    width = 6,
  )
)

server <- function(input, output, session) {
  m <- matrix(0, nrow = input$rows, ncol = input$columns)
}

shinyApp(ui, server)

CodePudding user response:

You need to use shinyMatrix::updateMatrixInput. The following example can be a starting point.

library(shiny)
library(shinyMatrix)

ui <- fluidPage(
  titlePanel("shinyMatrix: Simple App"),
  sidebarPanel(
    width = 6,
    numericInput("rows", "Number of rows:", "", min = 2, max = 100),
    numericInput("columns", "Number of columns:", "", min = 2, max = 100),
  ),
  mainPanel(
    matrixInput("matrix1",
      value = matrix(NA, 2,2),
      rows = list(
        names = TRUE,
        editableNames = TRUE),
      cols = list(
        names = TRUE,
        editableNames = TRUE
      ),
      class = "numeric"),
    width = 6,
  )
)

server <- function(input, output, session) {
    observe({
        m <- matrix(0, nrow = input$rows, ncol = input$columns)
        updateMatrixInput(session, "matrix1", m)
    })
}
  • Related