blob: 6304e363bfe494766259e81759d191d2e738158c [file] [log] [blame]
Hao Zhu37975a32019-01-15 14:59:34 -06001---
2title: "Use kableExtra and xml2 in the HARD way"
3author: "Hao"
4date: "1/15/2019"
5output: html_document
6---
7
8```{r setup, include=FALSE}
9knitr::opts_chunk$set(echo = TRUE)
10```
11
12Behind the scene, for HTML tables, `kableExtra` uses `xml2` to add styles and new contents to existing table. `kableExtra` is trying its best to get you the result in a literal way but in some rare case, I hope you can have the ability to freedom to be a HTML Ninja (quoting @yihui's xaringan). :)
13
14In `kableExtra` 1.0, I exported two functions that were previously used internally in this package: `kable_as_xml` and `xml_as_kable`. Here is an example for how to use these 2 function and xml2 to hack your table and do something `kableExtra` is not capable to do (at least right now).
15
16```{r}
17library(kableExtra)
18library(xml2)
19
20demo <- kable(mtcars[1:5, 1:5]) %>% # As always, mtcars ;)
21 kable_styling(full_width = F) %>%
22 kable_as_xml()
23
24demo %>% # Transform to xml
25 xml_child(2) %>% # Select <tbody> (1 is <thead>)
26 xml_child(2) %>% # Select 2nd row <tr> in <tbody>
27 xml_child(1) %>% # Select 1st cell in 2nd row <td>
28 xml_set_attr("style", "background: red; color: white;") # Add attribute to style
29
30xml_as_kable(demo) # Render that xml back as kable
31```
32
33For those `%>%` fans, keep in mind that since `xml2` makes modification to an external xml object. Although it looks like you can put everything in one pipe, the reality is that you will have to save the entire xml first, run the `xml2` code and then get it rendered.