You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R Shiny响应式表格中获取点击选中单元格的值?

问题解决:Shiny DT表格选中单元格无法获取值

问题说明

创建了一个R Shiny应用,支持输入文本生成可点击表格,但仅能获取选中单元格的行号和列号,无法获取单元格的实际值(返回为空)。

原代码

library(shiny)
library(dplyr)
library(DT)

ui <- fluidPage(
  textInput("caption", "Saisir votre addresse", ""),
  theme = bs_theme(version = 4, bootswatch = "minty"),
  mainPanel(
  width = 8,
  dataTableOutput('my_table')
  ),
  mainPanel( textOutput("selected_text") )
) 

server <- function(input, output) {
  
  output$my_table = DT::renderDataTable(as.data.frame(input$caption),selection = list(mode = "single", target = "cell"),options = list(paging = FALSE,searching = FALSE)) 
  
  observeEvent(input$my_table_cells_selected, {
    info <- input$my_table_cells_selected
    output$selected_text <- renderText({
      paste(info) # info[3] for value 
    }) 
  }) #Observe event
  
} # server

shinyApp(ui, server)

问题原因

input$my_table_cells_selected仅返回选中单元格的行索引和列索引(格式为c(行号, 列号)),并不包含单元格的实际值。需要根据这两个索引从表格对应的数据源中提取对应值。

修正后的代码

library(shiny)
library(dplyr)
library(DT)

ui <- fluidPage(
  textInput("caption", "Saisir votre addresse", ""),
  theme = bs_theme(version = 4, bootswatch = "minty"),
  mainPanel(
    width = 8,
    dataTableOutput('my_table')
  ),
  mainPanel( textOutput("selected_text") )
) 

server <- function(input, output) {
  
  # 将输入文本转为反应式数据源,避免重复转换
  table_data <- reactive({
    as.data.frame(input$caption)
  })
  
  output$my_table = DT::renderDataTable(
    table_data(),
    selection = list(mode = "single", target = "cell"),
    options = list(paging = FALSE, searching = FALSE)
  ) 
  
  observeEvent(input$my_table_cells_selected, {
    info <- input$my_table_cells_selected
    output$selected_text <- renderText({
      # 根据行列索引提取单元格值
      table_data()[info[1], info[2]]
    }) 
  }) #Observe event
  
} # server

shinyApp(ui, server)

修正说明

  1. 新增table_data反应式对象,统一管理表格数据源,避免在多处重复执行as.data.frame(input$caption),提升代码效率与可维护性。
  2. 在renderText中,通过table_data()[info[1], info[2]]直接根据选中的行号(info[1])和列号(info[2])提取单元格实际值,替代原代码仅输出索引的逻辑。

内容的提问来源于stack exchange,提问作者Laura Lisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:13:59