r - 向 Shiny DT 添加按钮以拉起模态
问题描述
我正在尝试在我的数据表中添加一列按钮,单击该按钮会弹出一个模式,但是我无法使用我在此处和此处在线找到的示例。
我的一些要求:
- 需要处理数据集中未知数量的行(可能是 5,可能是 10,可能是 500)
- 每个按钮都需要是唯一的 id,我可以使用它来引用行(在示例中,您可以看到我将行号拉入模态 - 现实生活中我使用行号来子集我的数据并实际将信息放入模态)
代码:
library(shiny)
library(shinydashboard)
library(DT)
ui = dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
DTOutput('x1'),
verbatimTextOutput("test")
)
)
server = function(input, output) {
##DATA TABLE WHERE I NEED A BUTTON##
output$x1 = renderDT(
iris,
selection = 'single',
options = list(
)
)
##MODAL CALLED BASED ON BUTTON CLICK
observeEvent(input$x1_cell_clicked, {
row = input$x1_cell_clicked$row
if (is.null(row) || row == '') {} else{
showModal(modalDialog(
title = paste0("Timeline!",row),
size = "s",
easyClose = TRUE,
footer = NULL
))
}
})
output$test <- renderPrint({
input$x1_cell_clicked$row
})
}
shinyApp(ui, server)
解决方案
在您的评论中,您询问了多个数据表的情况。是你想要的吗?
library(shiny)
library(DT)
button <- function(tbl){
function(i){
sprintf(
'<button id="button_%s_%d" type="button" onclick="%s">Click me</button>',
tbl, i, "Shiny.setInputValue('button', this.id);")
}
}
dat1 <- cbind(iris,
button = sapply(1:nrow(iris), button("tbl1")),
stringsAsFactors = FALSE)
dat2 <- cbind(mtcars,
button = sapply(1:nrow(mtcars), button("tbl2")),
stringsAsFactors = FALSE)
ui <- fluidPage(
fluidRow(
column(
width = 6,
DTOutput("tbl1", height = "500px")
),
column(
width = 6,
DTOutput("tbl2", height = "500px")
)
)
)
server <- function(input, output){
output[["tbl1"]] <- renderDT({
datatable(dat1, escape = ncol(dat1)-1, fillContainer = TRUE)
})
output[["tbl2"]] <- renderDT({
datatable(dat2, escape = ncol(dat2)-1, fillContainer = TRUE)
})
observeEvent(input[["button"]], {
splitID <- strsplit(input[["button"]], "_")[[1]]
tbl <- splitID[2]
row <- splitID[3]
showModal(modalDialog(
title = paste0("Row ", row, " of table ", tbl, " clicked"),
size = "s",
easyClose = TRUE,
footer = NULL
))
})
}
shinyApp(ui, server)
推荐阅读
- java - 使用 java 8 流过滤列表中的对象
- git - git按规则忽略指定类型的文件更改
- python - 在 Pygame 中从屏幕右侧发送障碍物
- oracle - 在 Oracle 中转换时区格式
- vba - 如何使用 vba 从 Object 获取元素 ID
- intellij-idea - 如何在 Intellij Platform SDK 中枚举编辑器及其位置?
- javascript - Blazor WASM 在不使用 JavaScript 的情况下处理 dom 元素
- c# - 在 C# 中针对浮点数验证整数值
- postgresql - 如何在 Postgresql 中更改 Effective_io_concurrency
- javascript - 如何使用 Ajax 调用在 API 中动态调用 ActionResult?