How to remove the name of first column of a table with collapse rows with rmarkdown and kableExtra
I'm doing a table with a combination of collapsed and packed rows. I want to remove the name the firstof the column, but when I do so kable removes the collapsing.
Any ideas?
Here an reproducible example code with the same errror:
library(tidyverse)
library(kableExtra)
data("iris")
Tbl <- iris %>%
pivot_longer(cols = c(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width)) %>%
separate(name, sep = 5, into = c("Flower_part", "Measure")) %>%
group_by(Species, Flower_part, Measure) %>%
summarise(Mean = mean(value),
SD = sd(value))
#Table with colapsed rows and the name of column
Tbl %>%
ungroup() %>%
select(-Species) %>%
kbl(digits = 3) %>%
kable_classic("striped", full_width = T) %>%
collapse_rows(columns = 1, valign = "top") %>%
pack_rows(index = table(Tbl$Species), indent = FALSE)
#Table with a "blank" name with the collapsing not working.
Tbl %>%
ungroup() %>%
select(-Species) %>%
rename(" " = "Flower_part") %>%
kbl(digits = 3) %>%
kable_classic("striped", full_width = T) %>%
collapse_rows(columns = 1, valign = "top") %>%
pack_rows(index = table(Tbl$Species), indent = FALSE)
Answers It seems like renaming the first column to a blank name disrupts the collapsing behavior in the table. To achieve your desired outcome without affecting the collapsing, you can use an alternative approach.
Instead of renaming the column to a blank name, you can keep the original column name but hide it visually using CSS. This way, the collapsing functionality will remain intact.
Here's how you can modify your code to achieve this:
library(tidyverse)
library(kableExtra)
data("iris")
Tbl <- iris %>%
pivot_longer(cols = c(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width)) %>%
separate(name, sep = 5, into = c("Flower_part", "Measure")) %>%
group_by(Species, Flower_part, Measure) %>%
summarise(Mean = mean(value),
SD = sd(value))
# Table with collapsed rows and hidden first column name
Tbl %>%
ungroup() %>%
select(-Species) %>%
kbl(digits = 3) %>%
kable_classic("striped", full_width = T) %>%
collapse_rows(columns = 1, valign = "top") %>%
pack_rows(index = table(Tbl$Species), indent = FALSE) %>%
column_spec(1, width = "0px") # Hide the first column visually using CSS
By using column_spec(1, width = "0px")
, we set the width of the first column to zero pixels, effectively hiding it from view while preserving the collapsing functionality.