kableExtra
软件包具有一个称为add_header_above()
的强大功能,该功能在输出表中的实际列名之上创建一个附加的标题行。这对于将数据分组非常有用。在fixed_thead = TRUE
中设置kable_styling()
时,向下滚动时会冻结实际的列名,但此附加的标题行不会冻结。
这是一个最小的shiny
应用程序,显示了我的意思。请注意,如果您在RStudio查看器中查看该应用程序,则正常的列标题和其他列标题都不会发粘。而是在适当的Web浏览器中运行它。
library(shiny)
library(magrittr)
ui <- fluidPage(
tableOutput("table")
)
server <- function(input, output, session) {
output$table <- function() {
knitr::kable(mtcars) %>%
kableExtra::kable_styling(fixed_thead = TRUE) %>%
kableExtra::add_header_above(c(" " = 1, "Header 1" = 5, "Header 2" = 6))
}
}
shinyApp(ui, server)
如何使使用
add_header_above()
创建的其他标题行具有粘性? 我想我需要在应用程序中合并一些CSS或JavaScript来这样做。
最佳答案
灵感来自@StéphaneLaurent的答案。以下是将sticky属性应用于任意数量的 header 的更通用的方法。
library(shiny)
library(magrittr)
JS <- "
$(document).ready(function() {
var myInterval = setInterval(function() {
// clear interval after the table's DOM is available
if ($('thead').length) {
clearInterval(myInterval);
}
// setting css
$('thead tr th').css('position', 'sticky').css('background', 'white');
var height = 0;
for (var i = 0, length = $('thead tr').length; i < length; i++) {
var header = $('thead tr:nth-child(' + i + ')');
height += header.length ? header.height() : 0;
$('thead tr:nth-child(' + (i + 1) + ') th').css('top', height);
}
}, 500);
});
"
ui <- fluidPage(
tags$head(
tags$script(HTML(JS))
),
tableOutput("table")
)
server <- function(input, output, session) {
output$table <- function() {
knitr::kable(mtcars) %>%
kableExtra::add_header_above(c(" " = 1, "Header 1" = 5, "Header 2" = 6)) %>%
kableExtra::add_header_above(c(" " = 1, "Header" = 11)) %>%
kableExtra::kable_styling()
}
}
shinyApp(ui, server)
如果您不希望主
app.R
具有所有Javascript,则可以将代码移至其他文件,请参见:Include a javascript file in Shiny app。
关于javascript - R Shiny-为电缆表添加额外的标题行 'sticky',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60514513/