In this simple example of R using Shiny package, how would I "subset" and show a specific column of data in an output table?

I´m trying to subset a user-generated input matrix in R´s shiny and shinyMatrix packages. I´d like to extract only the values of a selected matrix column (column 3 for example) in the 2nd output table ("table2") generated by this code. The first output table ("table1") simply mimics the user inputs which works fine. I´m trying to get the second output table to show only a selected column. This will show me how to subset input data, to implement an additional function waiting in the wings.

[Side note: when running this the user may add to matrix by clicking on the bottom row of the matrix - a very nice feature! If this input feature doesn´t work well for you, it doesn´t matter for purposes of addressing this question. If you´d like it to work perfectly, then download the latest version of shinyMatrix using devtools::install_github('INWTlab/shiny-matrix'); it won´t be available on CRAN for a while.]

library(shiny)
library(shinyMatrix)

m <- diag(3)
colnames(m) <- 1:3
rownames(m) <- letters[1:3]

ui <- fluidPage(
  titlePanel("Demo Matrix Input Field"),
  fluidRow(
    column(6, matrixInput(
                inputId = "matrix",
                label = "Default matrix",
                value = m,
                class = "numeric",
                cols = list(names = TRUE,editableNames = TRUE),
                rows = list(extend = TRUE,names = TRUE,editableNames = TRUE)
              )
    ),
    column(6, tableOutput("table1")),
    column(6, tableOutput("table2")), 
  )
)

server <- function(input, output, session) {
  
  output$table1 <- renderTable(input$matrix, rownames = TRUE)
  output$table2 <- renderTable(input$matrix, rownames = TRUE)
}

shinyApp(ui, server)

Here´s what running this code looks like, I´d like that 2nd table on the bottom right to show, for example, only the column tagged 3, using subsetting:

enter image description here

Upvotes: 0

Views: 339

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

You can use input$matrix[, 3] to show only the 3rd column in table2.

library(shiny)
library(shinyMatrix)

m <- diag(3)
colnames(m) <- 1:3
rownames(m) <- letters[1:3]

ui <- fluidPage(
  titlePanel("Demo Matrix Input Field"),
  fluidRow(
    column(6, matrixInput(
      inputId = "matrix",
      label = "Default matrix",
      value = m,
      class = "numeric",
      cols = list(names = TRUE,editableNames = TRUE),
      rows = list(extend = TRUE,names = TRUE,editableNames = TRUE)
    )
    ),
    column(6, tableOutput("table1")),
    column(6, tableOutput("table2")), 
  )
)

server <- function(input, output, session) {
  
  output$table1 <- renderTable(input$matrix, rownames = TRUE)
  output$table2 <- renderTable(input$matrix[, 3], rownames = TRUE)
}

shinyApp(ui, server)

Upvotes: 1

Related Questions