Marissa
Marissa

Reputation: 385

KableExtra using row_spec in collapsed rows

I have a dataset that is set up like the following mtcars summary:

mtcarssumm <- mtcars %>%
  group_by(cyl, gear) %>% 
  summarise(meanMPG = mean(mpg)) %>% 
  mutate(gear=as.character(gear)) %>% 
  bind_rows(group_by(mtcars,cyl) %>% 
  summarise(meanMPG=mean(mpg)) %>% 
  mutate(gear='Total')) %>% 
  arrange(cyl)

cyl gear  meanMPG
   <dbl> <chr>   <dbl>
 1     4 3        21.5
 2     4 4        26.9
 3     4 5        28.2
 4     4 Total    26.7
 5     6 3        19.8
 6     6 4        19.8
 7     6 5        19.7
 8     6 Total    19.7
 9     8 3        15.0
10     8 5        15.4
11     8 Total    15.1

What I would like is to create a table using kableextra, where the rows with gear = Total to be shaded. I'm currently using row_spec to do this. I'm also using collapse_rows to collapse down the repeated values in cyl:

mtcarssumm %>%
  kbl(booktabs = TRUE) %>% 
  collapse_rows(1, latex_hline = "major", valign = "middle") %>% 
  kable_styling() %>% 
  row_spec(which(mtcarssumm$gear == "Total"), background = "#e5e5e5")

When I convert to PDF, the entire row is shaded, as in the image below.

enter image description here

Is there a way to use collapse_rows and row_spec so the shading is only in the rows that are not collapsed? (Note, this code gives the desired result in HTML output but not in PDF output.

Thank you!

Upvotes: 0

Views: 2335

Answers (1)

Marissa
Marissa

Reputation: 385

I figured out a fix - I changed the first column's background (the collapsed one)

mtcarssumm %>% 
  kbl(booktabs = TRUE) %>% 
  collapse_rows(1,latex_hline = "major", valign = "middle") %>% 
  kable_styling() %>% 
  row_spec(which(mtcarssumm$gear == "Total"), background = "#e5e5e5") %>%
  column_spec(1, background = "white")

enter image description here

Upvotes: 0

Related Questions