Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

r markdown - KableExtra using row_spec in collapsed rows

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

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!

question from:https://stackoverflow.com/questions/65890454/kableextra-using-row-spec-in-collapsed-rows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...