using kable extra make subheaders and headers with repeating value columns in r

To create subheaders and headers with repeating value columns using kableExtra in R, you can use the following approach:

First, install and load the necessary packages:

main.r
install.packages(c("kableExtra", "dplyr"))
library(kableExtra)
library(dplyr)
78 chars
4 lines

Create a sample data frame:

main.r
df <- data.frame(
  Category = c("A", "A", "B", "B", "C", "C"),
  Subcategory = c("X", "Y", "X", "Y", "X", "Y"),
  Value1 = c(1, 2, 3, 4, 5, 6),
  Value2 = c(7, 8, 9, 10, 11, 12)
)
181 chars
7 lines

Use kable and kable_styling from kableExtra to create a table with subheaders and headers:

main.r
kable(df, rownames = FALSE) %>%
  kable_styling() %>%
  add_header_above(c(" " = 1, "Category" = 1, "Values" = 2)) %>%
  add_header_below(c(" " = 1, " " = 1, "Value1" = 1, "Value2" = 1)) %>%
  column_spec(2, bold = TRUE) %>%
  column_spec(3:4, italic = TRUE) %>%
  footnote(general = "Source: example data")
308 chars
8 lines

However, to make the headers repeat for every category, you need to reshape your data and add the headers manually. Here's how you can do it:

main.r
library(data.table)
library(dplyr)

# Reshape the data
df <- data.frame(
  Category = c("A", "A", "B", "B", "C", "C"),
  Subcategory = c("X", "Y", "X", "Y", "X", "Y"),
  Value1 = c(1, 2, 3, 4, 5, 6),
  Value2 = c(7, 8, 9, 10, 11, 12)
)

# Add header for each category
df_grouped <- df %>%
  group_by(Category) %>%
  summarise(
    `Subcategory\nValue1` = paste0(Subcategory, "\n", Value1),
    `Subcategory\nValue2` = paste0(Subcategory, "\n", Value2)
  ) %>%
  ungroup() %>%
  mutate(
    `Category\nSubcategory` = Category
  ) %>%
  select(`Category\nSubcategory`, `Subcategory\nValue1`, `Subcategory\nValue2`)

# Create the table
kable(df_grouped, rownames = FALSE) %>%
  kable_styling() %>%
  add_header_above(c(" " = 1, "Values" = 2)) %>%
  column_spec(1, bold = TRUE) %>%
  footnote(general = "Source: example data")
823 chars
31 lines

Note that this will require you to rearrange your data and might not work perfectly for every scenario. However, it should give you an idea of how to approach the problem.

You can adjust the style and format as needed to fit your requirements. Also, you can create more complex tables with different types of headers and subheaders.

Always make sure to check the kableExtra documentation for the most up-to-date information on its functionality.

Tags: r, kableExtra, data.table, dplyr.

related categories

gistlibby LogSnag