【问题标题】:Shiny: How can I create action links in a table based on the data, and then perform a filter using data from the link?Shiny:如何根据数据在表中创建操作链接,然后使用链接中的数据执行过滤?
【发布时间】:2022-01-19 07:59:36
【问题描述】:

我有两个共享密钥的表。第一个表始终显示在 UI 中。我希望用户能够单击表中的链接,然后显示一个模态对话框,该对话框是根据单击的链接过滤的第二个表。

具体示例:将mtcars 显示为表格,并带有gear 列的可点击链接。当单击一个时,例如4,会出现一个模式对话框,显示所有具有 4 个齿轮的汽车。如果点击3,您将获得所有具有 3 个齿轮的汽车。

似乎无论如何都没有使用shiny::actionLink() 传递参数,这是我假设我想用于表格链接的参数。我意识到下面的示例没有正确创建链接,但不知道第二步是如何工作的(作用于链接),我只是留下了一些伪代码作为示例。

library(shiny)
library(tidyverse)


ui <- fluidPage(

    # Application title
    titlePanel("mtcars"),

        mainPanel(
           tableOutput("table")
        )
    )


server <- function(input, output) {

    output$table <- renderTable({
        mtcars %>% 
            mutate(gear = actionLink("gearinput", label = gear)) #I realize this does not work, just leaving here as pseudo code.
    })
    
    observeEvent(input$gearinput, {
      showModal(modalDialog(
        title = "Gear filter",
        mtcars %>% filter(gear == input$gearinput)), #I can't figure out how to actually get the value based on the link clicked
      )
    })
     
    
}

# Run the application 
shinyApp(ui = ui, server = server)


【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我对@9​​87654325@不是很熟悉,所以我切换到data.table

    我们可以为actionLinks添加一个onclick事件,并通过Shiny.setInputValue将点击的齿轮提供给闪亮:

    library(shiny)
    # library(dplyr)
    library(data.table)
    
    DT <- copy(mtcars)
    setDT(DT)
    
    ui <- fluidPage(
      titlePanel("mtcars"),
      mainPanel(
        tableOutput("table")
      )
    )
    
    server <- function(input, output) {
      
      output$table <- renderTable({
        DT[, inputId := paste0("gear_input_", seq_len(.N))][, gear_links := as.character(actionLink(inputId = inputId, label = inputId, onclick = sprintf("Shiny.setInputValue(id = 'gear_click', value = %s);", gear))), by = inputId][, inputId := NULL]
      }, sanitize.text.function = function(x){x})
      
      observeEvent(input$gear_click, {
        showModal(modalDialog(
          title = "Gear filter",
          tableOutput("filtered_table"),
          size = "xl"
        ))
      })
      
      output$filtered_table <- renderTable({
        req(input$gear_click)
        DT[gear == input$gear_click][, c("gear_links", "vs") := NULL]
      })
      
    }
    
    shinyApp(ui = ui, server = server)
    

    您可能希望将链接的标签更改为 gear - 但这样更易于理解。

    关于此的有用链接:

    r shiny table not rendering html

    https://shiny.rstudio.com/articles/communicating-with-js.html

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多