打印数据表中选定单元格的值

Print the value of a selected cell from a datatable

我想在单击所选单元格时提取其值而不是其行和列坐标,因为我想将其用作另一个过程的输入。

library(shiny)
library(DT)
data("mtcars")

ui <- shinyUI(
  fluidRow(
    DT::dataTableOutput("myDatatable"),
    verbatimTextOutput("selectedCells")
  )
)

server <- shinyServer(function(input, output, session) {
  output$myDatatable <- DT::renderDataTable(mtcars, 
                                            selection=list(mode="single", target="cell"),
                                            server = FALSE,
                                            rownames=FALSE)

  output$selectedCells <- renderPrint(input$myDatatable_cells_selected)
})

shinyApp(ui, server)

您可以使用行号和列号访问 table 中的值,如下所示:

library(shiny)
library(DT)
data("mtcars")

ui <- shinyUI(fluidRow(
    DT::dataTableOutput("myDatatable"),
    verbatimTextOutput("selectedCells")
))

server <- shinyServer(function(input, output, session) {
    output$myDatatable <- DT::renderDataTable(
        mtcars,
        selection = list(mode = "single", target =
                             "cell"),
        server = FALSE,
        rownames = FALSE
    )

    output$selectedCells <- renderPrint({
        s = input$myDatatable_cells_selected
        if (!is.null(s) && ncol(s) != 0) {
            mtcars[s[1, 1] , s[1, 2] + 1]
        } else {
            NULL
        }
    })
})

shinyApp(ui, server)

如您所见,必须将一个添加到列值以指定适当的位置。处理未选择的案例也很重要。