首页 > 解决方案 > 将闪亮的 DT 单元格值传递给函数

问题描述

我有一个使用 function1 和用户输入构建的数据表。然后,我想使用此数据表中的单元格值作为 function2 的输入来构建另一个数据表。我收到过滤器错误,并认为问题与我选择单元格值的方式有关。我在这里构建一个现有的 SO 解决方案。

假设我们有 iris 数据并且 function1 使用用户输入来过滤物种。function1 的结果是响应式调用的结果。现在 function2 将此结果作为输入,并使用选定的“单元格”值 (Sepal.Length) 进一步过滤和构建另一个数据表。

感谢@Silentdevildoll 的评论,table2 的构造正确(我认为),但我仍然看到这个错误:

警告:错误:filter()输入有问题..1。i 输入..1Sepal.Length == var。x 输入..1的大小必须为 50 或 1,而不是 0。

library(shiny)
library(DT)

ui <- fluidPage(
 
  mainPanel(
    fluidRow(
      column(4, textInput('textInput1', label=NULL)),
      column(1, actionButton('button1', label=NULL))
    ),
    fluidRow(
      column(8, DT::dataTableOutput("table1")),
      column(4, DT::dataTableOutput("table2"))
    )
  )
)

server <- function(input, output, session){
  
   data(iris)



function1 <- function(id){
    return(dplyr::filter(iris, Species==id))
  }
  
  function2 <- function(df, var){
    return(dplyr::filter(df, Sepal.Length==var))  
  }
  
  data <- reactiveValues()
  
  observeEvent(input$button1, { data$ID <- input$textInput1 })

  table1_rec <- reactive({ function1(data$ID) })
  
  output$table1 <- DT::renderDataTable({
    req(data$ID)
    DT::datatable(table1_rec(), selection = list(target = 'cell'))
                    
  })
  
  table2_rec <- reactive({ 
    selected = table1_rec()[input$table1_cells_selected]
    function2(table1_rec(), selected) 
  })
  
  output$table2 <- DT::renderDataTable({
    DT::datatable(table2_rec())
  })

}

shinyApp(ui, server)

标签: rshinydt

解决方案


推荐阅读