12

我想用 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))

我很高兴你的建议。

4

2 回答 2

13

标头是一个以 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)
于 2017-07-20T08:06:53.063 回答
7

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))
于 2019-09-17T09:22:22.020 回答