R:使用数据框列中的信息作为 KableExtra 中的标题

R: Use information from column of dataframe for caption in KableExtra

使用 gt() 您可以使标题除了文本之外还包含来自数据框的信息:

table_name <- paste(data$`column_data`[1],paste("Sample Text"))
  table <- gt(data,
              rownames_to_stub = TRUE) %>%
    
    tab_header(title = table_name)

有没有办法让 KableExtra 做到这一点?

是的,通过向 add_header_above() 函数的 header 参数提供数据框。根据这个论点的文档:

Alternatively, a data frame with two columns can be provided: The first column should contain the header names (character vector) and the second column should contain the colspan (numeric vector).

一个{gt}table

mtcars |> 
  head(c(5,4)) |> 
  gt(rownames_to_stub = TRUE) |> 
  tab_header(paste(mtcars$drat[1], paste("Sample Text")))

结果:

一个{kableExtra}table

mtcars |> 
 head(c(5,4)) |> 
 kable() |> 
 kable_styling(full_width = FALSE) |> 
 add_header_above(
     data.frame(
       text = paste(mtcars$drat[1],"Sample Text"), 
       span = 5))  # The number 5 is used to match the number of columns

结果: