Home > front end >  R: Use information from column of dataframe for caption in KableExtra
R: Use information from column of dataframe for caption in KableExtra

Time:05-11

Using gt() you can make the title include information from the data frame in addition to text:

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

Is there a way to make KableExtra do this?

CodePudding user response:

Yes, by supplying a data frame to the header argument of add_header_above() function. According to the documentation of this argument:

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

A {gt} table

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

The result:

enter image description here

A {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

The result:

enter image description here

  • Related