I'm using the kableExtra
package in R to create a table with styled headers, but I’m having trouble applying the same background color to header cells that are blank. When I use add_header_above
with empty placeholders, they default to white, while non-empty placeholders in add_header_above
receive the specified background color.
Here's an example of my code:
library(kableExtra)
# Sample data
results_df <- data.frame(
visit = c("Visit 1", "Visit 2", "Visit 3"),
n = c(100, 95, 90),
raw_mean = c(10.2, 9.8, 8.7),
raw_ci_lower = c(9.5, 9.1, 8.0),
raw_ci_upper = c(10.9, 10.5, 9.4),
adjusted_mean = c(10.0, 9.6, 8.5),
adj_ci_lower = c(9.3, 8.9, 7.8),
adj_ci_upper = c(10.7, 10.3, 9.2),
adjustment_warning = c("None", "High variance", "None")
)
# Generate table
results_df %>%
kable("html", col.names = c("Visit", "N", "Raw Mean", "Raw CI Lower", "Raw CI Upper",
"Adjusted Mean", "Adj. CI Lower", "Adj. CI Upper", "Warning")) %>%
kable_styling(bootstrap_options = c("striped"),
font_size = 16,
full_width = TRUE,
position = "center") %>%
add_header_above(c(" " = 2, "Raw Data" = 3, "Adjusted Data" = 3, " " = 1),
background = "#1482FA", color = "#FFFFFF") %>%
row_spec(0, bold = TRUE, background = "#1482FA", color = "#FFFFFF")
Any idea how I can fix that?
One option or workaround would be to use some placeholder text for which you set the color=
to "transparent"
:
library(kableExtra)
# Sample data
results_df <- data.frame(
visit = c("Visit 1", "Visit 2", "Visit 3"),
n = c(100, 95, 90),
raw_mean = c(10.2, 9.8, 8.7),
raw_ci_lower = c(9.5, 9.1, 8.0),
raw_ci_upper = c(10.9, 10.5, 9.4),
adjusted_mean = c(10.0, 9.6, 8.5),
adj_ci_lower = c(9.3, 8.9, 7.8),
adj_ci_upper = c(10.7, 10.3, 9.2),
adjustment_warning = c("None", "High variance", "None")
)
# Generate table
results_df %>%
kable("html",
col.names = c(
"Visit", "N", "Raw Mean", "Raw CI Lower", "Raw CI Upper",
"Adjusted Mean", "Adj. CI Lower", "Adj. CI Upper", "Warning"
)
) %>%
kable_styling(
bootstrap_options = c("striped"),
font_size = 16,
full_width = TRUE,
position = "center"
) %>%
add_header_above(c("Foo" = 2, "Raw Data" = 3, "Adjusted Data" = 3, "Foo" = 1),
background = "#1482FA",
color = c("transparent", "#FFFFFF", "#FFFFFF", "transparent")
) %>%
row_spec(0, bold = TRUE, background = "#1482FA", color = "#FFFFFF")