kableExtra:动态add_header_above标签

时间:2017-07-20 06:32:47

标签: r knitr r-markdown pandoc kableextra

我想用rmarkdown创建一个pdf。 PDF应包含一个表格。该表应具有动态列标签。

标签应显示日历周。

但是,不显示日历周(例如,KW29),而是显示变量名称" kw0"。

我的错误是什么?

library(knitr)
library(kableExtra)
library(lubridate)
options(knitr.table.format = "latex")
loadData <- function() {# load some data}

myData<- loadData ()

kw0 <- paste("KW", week(Sys.Date()) - 1, sep = "")
kw1 <- paste("KW", week(Sys.Date()), sep = "")
kw2 <- paste("KW", week(Sys.Date()) + 1, sep = "")
kw3 <- paste("KW", week(Sys.Date()) + 2, sep = "")


kable(myData, row.names = FALSE, booktabs = T) %>%
  kable_styling(
  full_width = TRUE,
  font_size = 14 
  )  %>% add_header_above(header = c(" " = 1, kw0 = 2, kw1 = 2, kw2 = 2, kw3 = 2))

我很高兴你的建议。

2 个答案:

答案 0 :(得分:9)

标题是一个命名字符向量,其中colspan为值。

您必须使用函数names()指定向量的名称。

library(knitr)
library(kableExtra)
library(lubridate)
options(knitr.table.format = "latex")
loadData <- function() {# load some data}

myData<- loadData ()

kw0 <- paste("KW", week(Sys.Date()) - 1, sep = "")
kw1 <- paste("KW", week(Sys.Date()), sep = "")
kw2 <- paste("KW", week(Sys.Date()) + 1, sep = "")
kw3 <- paste("KW", week(Sys.Date()) + 2, sep = "")

# Set a named vector for dynamic header

# create vector with colspan
myHeader <- c(" " = 2, kw0 = 2, kw1 = 2, kw2 = 2, kw3 = 2)

# set vector names 
names(myHeader) <- c(" ", kw0, kw1, kw2, kw3)

kable(myData, row.names = FALSE, booktabs = T) %>%
  kable_styling(
  full_width = TRUE,
  font_size = 14 
  )  %>% add_header_above(header = myHeader)

答案 1 :(得分:3)

kableExtra开发人员的github页面上描述了一种简便快捷的方法:https://github.com/haozhu233/kableExtra/issues/415

library(knitr)
library(kableExtra)
library(lubridate)
options(knitr.table.format = "latex")
loadData <- function() {# load some data}

myData<- loadData ()

kw0 <- paste("KW", week(Sys.Date()) - 1, sep = "")
kw1 <- paste("KW", week(Sys.Date()), sep = "")
kw2 <- paste("KW", week(Sys.Date()) + 1, sep = "")
kw3 <- paste("KW", week(Sys.Date()) + 2, sep = "")


kable(myData, row.names = FALSE, booktabs = T) %>%
  kable_styling(
  full_width = TRUE,
  font_size = 14 
  )  %>% add_header_above(header = c(" " = 1, setNames(2,kw0), setNames(2,kw1), setNames(2,kw2), setNames(2,kw3))