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

如何将Shiny中DT组件的选中行向量转换为data.frame?

解决Shiny中DT选中行索引转data.frame的错误

错误原因

你遇到的cannot coerce class ‘c("reactiveExpr", "reactive", "function")’ to a data.frame错误,是因为直接将reactive()返回的响应式函数对象传给了as.data.frame()。reactive()的返回值不是具体的数值向量,而是一个需要调用(加括号)才能获取值的响应式对象。

解决步骤

  1. 先定义响应式对象存储选中行索引
  2. 在响应式上下文内调用该对象获取值,再转换为data.frame
  3. 若需在其他模块复用,将转换后的data.frame也定义为响应式对象

修改后的完整代码

library(shiny)
library(glue)
library(dplyr)
library(DT)
library(shinyWidgets)
library(tibble)
library(stringr) # 补充依赖,原代码中用到了stringr::str_pad

####Create the matrix and organization for the 96 well plate####
plate96 <- function(id) {
  div(
    style = "position: relative; height: 500px",
    tags$style(HTML('
          
        .wells {
            transform: translateX(50%);
        }

        .wells tbody tr td:not(:first-of-type) {
            border: 1px solid black;
            height: 15px;
            width: 15px;
            padding: 15px;
            font-size: 0;
        }

    ')),
    div(
      style = "position: absolute; left: 50%; transform: translateX(-100%);",
      div(
        class = "wells",
        DTOutput(id, width = "90%", height= "100%")
      )
    )
  )
}


renderPlate96 = function(id, colors = rep("white", 96)) {
  stopifnot(is.character(colors) && length(colors) == 96)
  
  plate <- matrix(1:96, 
                  nrow = 8, 
                  ncol = 12, 
                  byrow = TRUE, 
                  dimnames = list(LETTERS[1:8], 1:12))
  
  colnames (plate) = stringr::str_pad(colnames(plate), 2, "left", "0")
  
  return(plate_return1 <-
           datatable(
             plate,
             options = list(dom = 't', ordering = F),
             selection = list(target = "row"),
             class = 'cell-border compact'
           ) %>%
           formatStyle(
             1:12,
             cursor = 'pointer',
             backgroundColor = styleEqual(1:96, colors, default = NULL)
           )
  )
  
}

ui <- fluidPage(
  br(),
  
  plate96("plate"),
  tags$b("Wells Selected (Row Indices):"),
  verbatimTextOutput("plateWells_selected"),
  tags$br(),
  tags$b("Selected Rows as Data Frame:"),
  verbatimTextOutput("selected_df_output")

)

server <- function(input, output, session){
  
  ####Create the 96 well plate image####
  output$plate <- renderDT({
    renderPlate96()
  })
  
  output$plateWells_selected <- renderPrint({
    input$plate_rows_selected
  })
  
  ####处理选中行并转成data.frame####
  # 定义响应式对象存储选中行索引
  selected_rows <- reactive(input$plate_rows_selected)
  
  # 定义响应式data.frame,仅在有选中行时生成
  selected_df <- reactive({
    req(selected_rows()) # 确保存在选中行,避免空值报错
    tibble(row_index = selected_rows()) # 转成tibble(data.frame的扩展)
  })
  
  # 输出查看转换后的data.frame
  output$selected_df_output <- renderPrint({
    selected_df()
  })
  
}
shinyApp(ui = ui, server = server)

关键修改点说明

  • selected_rows <- reactive(input$plate_rows_selected):将选中行索引包装为响应式对象,随用户选择实时更新
  • selected_df <- reactive({...}):在响应式上下文内,调用selected_rows()获取当前选中的索引向量,再转换为data.frame;req()用于避免未选中任何行时出现空值错误
  • 新增UI输出selected_df_output,用于验证转换结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:06:16