在这个使用 Shiny 包的简单 R 示例中,我将如何 "subset" 并在输出 table 中显示特定的数据列?

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

我正在尝试在 R 的 shiny 和 shinyMatrix 包中对用户生成的输入矩阵进行子集化。我想在此代码生成的第二个输出 table ("table2") 中仅提取选定矩阵列(例如第 3 列)的值。第一个输出 table ("table1") 只是模仿用户输入,效果很好。我试图让第二个输出 table 只显示选定的列。这将向我展示如何对输入数据进行子集化,以实现等待中的附加功能。

[旁注:当 运行 时,用户可以通过单击矩阵的底行来添加到矩阵 - 这是一个非常好的功能!如果此输入功能对您来说效果不佳,那么对于解决此问题而言并不重要。如果您希望它完美运行,请使用 devtools::install_github('INWTlab/shiny-matrix') 下载最新版本的 shinyMatrix;它暂时不会在 CRAN 上可用。]

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)

这是 运行 这段代码的样子,我希望右下角的第二个 table 使用子集仅显示标记为 3 的列:

您可以使用 input$matrix[, 3] 仅显示表 2 中的第 3 列。

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)