[英]Workaround for issues with freezing header in DT::datatable() in R Shiny
I am using DT::datatable() in an R Shiny app to render a table with the header and first column fixed.我在 R Shiny 应用程序中使用 DT::datatable() 来呈现一个表,其中表头和第一列是固定的。 My app has multiple tabs.
我的应用程序有多个选项卡。 I've tried two different approaches but both have bugs that make them unusable.
我尝试了两种不同的方法,但都存在使它们无法使用的错误。 I'm aware that these issues have been reported but I was wondering if anyone knows a workaround that would work in my case.
我知道已经报告了这些问题,但我想知道是否有人知道适用于我的情况的解决方法。
Approach # 1: scrollY方法#1:scrollY
Here I set scrollY = "500px"
in options.在这里,我在选项中设置了
scrollY = "500px"
。 The problem is that when I change the number of entries to something other than 10, when I scroll to the bottom, the first column is misaligned with the other columns.问题是,当我将条目数更改为 10 以外的内容时,当我滚动到底部时,第一列与其他列未对齐。
require(shiny)
require(DT)
shinyApp(
ui = tabsetPanel(
tabPanel(
title = "Tab 1",
fluidPage(
DTOutput("table1")
)
),
tabPanel(
title = "Tab 2",
fluidPage(
plotOutput("myPlot"),
DTOutput("table2")
)
)
),
server = function(input, output, session) {
output$table1 <- DT::renderDataTable({
myData <- cbind(iris, iris, iris, iris)
colnames(myData) <- paste0("Column ", 1:ncol(myData))
DT::datatable(
data = myData,
extensions = "FixedColumns",
rownames = F,
options = list(
scrollX = T,
scrollY = "500px",
fixedColumns = list(leftColumns = 1)
)
)
})
output$myPlot <- renderPlot({
plot(1:10, 1:10)
})
output$table2 <- DT::renderDataTable({
DT::datatable(iris)
})
}
)
Approach # 2: FixedHeader extension方法#2:FixedHeader 扩展
Here I use the FixedHeader extension and set fixedHeader = T
in options.这里我使用 FixedHeader 扩展并在选项中设置
fixedHeader = T
。 This avoids the issue with approach # 1, but it has a more serious issue.这避免了方法#1 的问题,但它有一个更严重的问题。 The fixed header from the table appears on other tabs.
表格中的固定标题出现在其他选项卡上。 In this example, if I scroll down the table on Tab 1, the headers remain fixed as expected, but when I switch to Tab 2 and scroll down, the fixed headers from the table on Tab 1 appear on Tab 2.
在此示例中,如果我向下滚动选项卡 1 上的表格,标题将按预期保持固定,但是当我切换到选项卡 2 并向下滚动时,选项卡 1 上的表格中的固定标题出现在选项卡 2 上。
require(shiny)
require(DT)
shinyApp(
ui = tabsetPanel(
tabPanel(
title = "Tab 1",
fluidPage(
DTOutput("table1")
)
),
tabPanel(
title = "Tab 2",
fluidPage(
plotOutput("myPlot"),
DTOutput("table2")
)
)
),
server = function(input, output, session) {
output$table1 <- DT::renderDataTable({
myData <- cbind(iris, iris, iris, iris)
colnames(myData) <- paste0("Column ", 1:ncol(myData))
DT::datatable(
data = myData,
extensions = c("FixedColumns", "FixedHeader"),
rownames = F,
options = list(
scrollX = T,
fixedHeader = T,
fixedColumns = list(leftColumns = 1)
)
)
})
output$myPlot <- renderPlot({
plot(1:10, 1:10)
})
output$table2 <- DT::renderDataTable({
DT::datatable(iris)
})
}
)
将 DT 从 0.19 版更新到 0.20 版(11/15/2021 发布)修复了该问题,因此方法 #1 可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.