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。
发布于 2020-03-04 04:05:11
灵感来自@Stéphane Laurent的回答。下面是将粘性属性应用于任意数量的头的一种更通用的方法。
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 )。
发布于 2020-03-03 21:07:02
library(shiny)
library(magrittr)
CSS <- "
thead tr th {
position: sticky;
background-color: white;
}
thead tr:nth-child(1) th {
top: 0;
}
"
JS <- "
$(document).ready(function(){
setTimeout(function(){
var h = $('thead tr:nth-child(1)').height();
$('thead tr:nth-child(2) th').css('top', h);
}, 500);
});
"
ui <- fluidPage(
tags$head(
tags$style(HTML(CSS)),
tags$script(HTML(JS))
),
uiOutput("table")
)
server <- function(input, output, session) {
output$table <- renderUI({
tabl <- knitr::kable(mtcars) %>%
kableExtra::add_header_above(c(" " = 1, "Header 1" = 5, "Header 2" = 6)) %>%
kableExtra::kable_styling()
HTML(tabl)
})
}
shinyApp(ui, server)https://stackoverflow.com/questions/60514513
复制相似问题