kableExtra: Dynamic add_header_above labeling

家住魔仙堡 提交于 2020-07-04 08:58:08

问题


I would like to create a pdf with rmarkdown. The PDF should contain a table. The table should have a dynamic column label.

The tabhead should display the calendar week.

However, the calendar week (e.g., KW29) is not displayed but the variable name "kw0".

What is my error?

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))

I am glad about your advice.


回答1:


The header is a named character vector with colspan as values.

You have to assign the names of the vector with the function 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)



回答2:


An easy and quick method is described on the kableExtra developer's github page: 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))


来源:https://stackoverflow.com/questions/45206908/kableextra-dynamic-add-header-above-labeling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!