我有一个值的数据框,我正在尝试将其渲染为 R Shiny 中的表格。我想要扩展某些值以占用多列,就像使用 HTML rowspan 属性一样。但是,如果我要这样做,我就必须从头开始创建整个表,而且我更愿意使用 DT 库来轻松地从我的数据表进行转换。
作为示例,我创建了以下脚本:
# ui.R
fluidPage(
DT::dataTableOutput("table")
)
# server.R
library(DT)
function(input, output) {
output$table <- DT::renderDataTable({
df <- data.frame(A = c("Trial 1", 1, 1, 1), B = c("", 1, 1, 1), C = c("", 1, 1, 1),
D = c("Trial 2", 2, 2, 2), E = c("", 2, 2, 2), F = c("", 2, 2, 2),
G = c("Trial 3", 3, 3, 3), H = c("", 3, 3, 3), I = c("", 3, 3, 3))
DT::datatable(df,
options = list(dom = "t",
ordering = FALSE))
})
}
此脚本呈现以下 UI:
如何展开包含“试验 1”、“试验 2”和“试验 3”的单元格,使它们各自占据三列?
最佳答案
我们可以使用自定义容器将列组名称添加为真实的列标题:
# ui.R
ui <- fluidPage(
DT::dataTableOutput("table")
)
# server.R
library(DT)
df <- data.frame(A = c(1, 1, 1), B = c(1, 1, 1), C = c(1, 1, 1),
D = c(2, 2, 2), E = c(2, 2, 2), F = c(2, 2, 2),
G = c(3, 3, 3), H = c(3, 3, 3), I = c(3, 3, 3))
myContainer <- htmltools::withTags(table(
class = 'display',
thead(
tr(
th(),
th(colspan = 3, 'Trial 1', class = "dt-center"),
th(colspan = 3, 'Trial 2', class = "dt-center"),
th(colspan = 3, 'Trial 3', class = "dt-center")
),
tr(
th(),
lapply(names(df), th)
)
)
))
server <- function(input, output) {
output$table <- DT::renderDataTable({
DT::datatable(df, container = myContainer,
options = list(dom = "t", ordering = FALSE,
columnDefs = list(list(className = "dt-center", targets = "_all"))
))
})
}
runApp(list(ui = ui, server = server))
输出:
或者,如果您确实希望第一行具有 colspan,我们可以使用 initComplete
选项在呈现表格时调用 JavaScript 函数。这里仅是服务器部分:
jsc <- '
function(settings, json) {
$("td:contains(\'Trial\')").attr("colspan", "3").css("text-align", "center");
$("tbody > tr:first-child > td:empty").remove();
}'
server <- function(input, output) {
output$table <- DT::renderDataTable({
df <- data.frame(A = c("Trial 1", 1, 1, 1), B = c("", 1, 1, 1), C = c("", 1, 1, 1),
D = c("Trial 2", 2, 2, 2), E = c("", 2, 2, 2), F = c("", 2, 2, 2),
G = c("Trial 3", 3, 3, 3), H = c("", 3, 3, 3), I = c("", 3, 3, 3))
DT::datatable(df, options = list(dom = "t", ordering = FALSE, initComplete = JS(jsc)))
})
}
在 JS 函数的第一行中,我们选择包含单词 Trial 的所有单元格,并添加相应的属性和样式。然后,我们选择所有空单元格,它们是行元素的直接后代,而行元素又是表主体的第一个子元素,并将它们从 DOM 中删除。 Here您可以找到有关 CSS 选择器的一般引用,例如 >
。
输出:
关于r - 在 R Shiny 中渲染时如何将表格单元格扩展到多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49803975/