blob: 2869f8da9255db70d5103d8d7b179ad417dae48b [file] [log] [blame]
Hao Zhu5e4dd502018-04-05 12:01:58 -04001---
2title: "用kableExtra做牛*的表格"
3author: "朱昊"
4date: "`r Sys.Date()`"
5output:
6 html_document:
7 theme: simplex
8 toc: true
9 toc_depth: 2
10 toc_float: true
11---
12
Hao Zhu222cd7e2018-04-10 14:27:19 -040013突然意识到这包写了都一年了还没写过中文doc,有些过意不去啊,赶紧补上。
Hao Zhu5e4dd502018-04-05 12:01:58 -040014
15另外这中文版我就不发CRAN了,要看的麻烦移步这包的文档网站[http://haozhu233.github.io/kableExtra/](http://haozhu233.github.io/kableExtra/)来看吧。
16
Hao Zhu222cd7e2018-04-10 14:27:19 -040017(因为我基本是在自由发挥。。你们不要太去在意中文英文的不同哈。。。)
Hao Zhu5e4dd502018-04-05 12:01:58 -040018
19# 简介
Hao Zhu222cd7e2018-04-10 14:27:19 -040020`kableExtra`的基本目标是帮你搭建以及美化一些常用而又较为复杂的表格。这些表格有个特点,那就是用word 或者excel来做会极其简单,而要用一个编程语言去描述往往反而会让人绝望,尤其是对于一些LaTeX初心者(比如当年的我。。)。而现在,在有了这个包的帮助下,我希望你能用一种更为直觉的方式来创建你的表格,把更多的时间花在内容上。而那些排版之类的脏活累活,我就先帮你给做啦。:)
Hao Zhu5e4dd502018-04-05 12:01:58 -040021
Hao Zhu222cd7e2018-04-10 14:27:19 -040022# 安装
23CRAN安装`install.packages("kableExtra")`不用我说,想尝鲜可以使用开发版。
Hao Zhu5e4dd502018-04-05 12:01:58 -040024```r
Hao Zhu5e4dd502018-04-05 12:01:58 -040025# install.packages("devtools")
26devtools::install_github("haozhu233/kableExtra")
27```
Hao Zhu222cd7e2018-04-10 14:27:19 -040028
29# 第一步
30
31
32
33## bootstrap了解一下
34如果你从没听过bootstrap的话,你可以去了解一下。简单来说,bootstrap是个开源的CSS库,可以用来很方便地美化HTML页面,也因此在RStudio的产品中被大量使用。你用rmarkdown和shiny生成出来的HTML文档和app都有加载。而这个包的HTML部分也提供了一些借口方便你快速实现一些bootstrap风的表格。
35
36在这份文档中,我们主要使用`mtcars`这个数据的前几列和几行数据来演示。
37
Hao Zhu5e4dd502018-04-05 12:01:58 -040038```{r}
39library(knitr)
40library(kableExtra)
41dt <- mtcars[1:5, 1:6]
42```
43
Hao Zhu222cd7e2018-04-10 14:27:19 -040044
Hao Zhu5e4dd502018-04-05 12:01:58 -040045When you are using `kable()`, if you don't specify `format`, by default it will generate a markdown table and let pandoc handle the conversion from markdown to HTML/PDF. This is the most favorable approach to render most simple tables as it is format independent. If you switch from HTML to pdf, you basically don't need to change anything in your code. However, markdown doesn't support complex table. For example, if you want to have a double-row header table, markdown just cannot provide you the functionality you need. As a result, when you have such a need, you should **define `format` in `kable()`** as either "html" or "latex". *You can also define a global option at the beginning using `options(knitr.table.format = "html")` so you don't repeat the step everytime.* **In this tutorial, I'll still put `format="html"` in the function in case users just want to quickly replicate the results.**
46
47```{r}
48options(knitr.table.format = "html")
49## If you don't define format here, you'll need put `format = "html"` in every kable function.
50```
51
52## Basic HTML table
53Basic HTML output of `kable` looks very crude. To the end, it's just a plain HTML table without any love from css.
54```{r}
55kable(dt, "html")
56```
57
58## Bootstrap theme
59When used on a HTML table, `kable_styling()` will automatically apply twitter bootstrap theme to the table. Now it should looks the same as the original pandoc output (the one when you don't specify `format` in `kable()`) but this time, you are controlling it.
60```{r}
61dt %>%
62 kable("html") %>%
63 kable_styling()
64```
65
66# Table Styles
67`kable_styling` offers a few other ways to customize the look of a HTML table.
68
69## Bootstrap table classes
70If you are familiar with twitter bootstrap, you probably have already known its predefined classes, including `striped`, `bordered`, `hover`, `condensed` and `responsive`. If you are not familiar, no worries, you can take a look at their [documentation site](http://getbootstrap.com/css/#tables) to get a sense of how they look like. All of these options are available here.
71
72For example, to add striped lines (alternative row colors) to your table and you want to highlight the hovered row, you can simply type:
73```{r}
74kable(dt, "html") %>%
75 kable_styling(bootstrap_options = c("striped", "hover"))
76```
77
78The option `condensed` can also be handy in many cases when you don't want your table to be too large. It has slightly shorter row height.
79```{r}
80kable(dt, "html") %>%
81 kable_styling(bootstrap_options = c("striped", "hover", "condensed"))
82```
83
84Tables with option `responsive` looks the same with others on a large screen. However, on a small screen like phone, they are horizontally scrollable. Please resize your window to see the result.
85```{r}
86kable(dt, "html") %>%
87 kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"))
88```
89
90## Full width?
91By default, a bootstrap table takes 100% of the width. It is supposed to use together with its grid system to scale the table properly. However, when you are writing a rmarkdown document, you probably don't want to write your own css/or grid. For some small tables with only few columns, a page wide table looks awful. To make it easier, you can specify whether you want the table to have `full_width` or not in `kable_styling`. By default, `full_width` is set to be `TRUE` for HTML tables (note that for LaTeX, the default is `FALSE` since I don't want to change the "common" looks unless you specified it.)
92```{r}
93kable(dt, "html") %>%
94 kable_styling(bootstrap_options = "striped", full_width = F)
95```
96
97## Position
98Table Position only matters when the table doesn't have `full_width`. You can choose to align the table to `center`, `left` or `right` side of the page
99```{r}
100kable(dt, "html") %>%
101 kable_styling(bootstrap_options = "striped", full_width = F, position = "left")
102```
103
104Becides these three common options, you can also wrap text around the table using the `float-left` or `float-right` options.
105```{r}
106kable(dt, "html") %>%
107 kable_styling(bootstrap_options = "striped", full_width = F, position = "float_right")
108```
109Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sit amet mauris in ex ultricies elementum vel rutrum dolor. Phasellus tempor convallis dui, in hendrerit mauris placerat scelerisque. Maecenas a accumsan enim, a maximus velit. Pellentesque in risus eget est faucibus convallis nec at nulla. Phasellus nec lacinia justo. Morbi fermentum, orci id varius accumsan, nibh neque porttitor ipsum, consectetur luctus risus arcu ac ex. Aenean a luctus augue. Suspendisse et auctor nisl. Suspendisse cursus ultrices quam non vulputate. Phasellus et pharetra neque, vel feugiat erat. Sed feugiat elit at mauris commodo consequat. Sed congue lectus id mattis hendrerit. Mauris turpis nisl, congue eget velit sed, imperdiet convallis magna. Nam accumsan urna risus, non feugiat odio vehicula eget.
110
111## Font size
112If one of your tables is huge and you want to use a smaller font size for that specific table, you can use the `font_size` option.
113```{r}
114kable(dt, "html") %>%
115 kable_styling(bootstrap_options = "striped", font_size = 7)
116```
117
118# Column / Row Specification
119## Column spec
120When you have a table with lots of explanatory texts, you may want to specified the column width for different column, since the auto adjust in HTML may not work in its best way while basic LaTeX table is really bad at handling text wrapping. Also, sometimes, you may want to highlight a column (e.g. a "Total" column) by making it bold. In these scenario, you can use `column_spec()`. You can find an example below.
121
122Warning: If you have a super long table, you should be cautious when you use `column_spec` as the xml node modification takes time.
123
124```{r}
125text_tbl <- data.frame(
126 Items = c("Item 1", "Item 2", "Item 3"),
127 Features = c(
128 "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin vehicula tempor ex. Morbi malesuada sagittis turpis, at venenatis nisl luctus a. ",
129 "In eu urna at magna luctus rhoncus quis in nisl. Fusce in velit varius, posuere risus et, cursus augue. Duis eleifend aliquam ante, a aliquet ex tincidunt in. ",
130 "Vivamus venenatis egestas eros ut tempus. Vivamus id est nisi. Aliquam molestie erat et sollicitudin venenatis. In ac lacus at velit scelerisque mattis. "
131 )
132)
133
134kable(text_tbl, "html") %>%
135 kable_styling(full_width = F) %>%
136 column_spec(1, bold = T, border_right = T) %>%
137 column_spec(2, width = "30em", background = "yellow")
138```
139
140
141## Row spec
142Similar with `column_spec`, you can define specifications for rows. Currently, you can either bold or italiciz an entire row. Note that, similar with other row-related functions in `kableExtra`, for the position of the target row, you don't need to count in header rows or the group labelling rows.
143
144```{r}
145kable(dt, "html") %>%
146 kable_styling("striped", full_width = F) %>%
147 column_spec(5:7, bold = T) %>%
148 row_spec(3:5, bold = T, color = "white", background = "#D7261E")
149```
150
151
152
153## Header Rows
154One special case of `row_spec` is that you can specify the format of the header row via `row_spec(row = 0, ...)`.
155```{r}
156kable(dt, format = "html") %>%
157 kable_styling("striped", full_width = F) %>%
158 row_spec(0, angle = -45)
159```
160
161# Cell/Text Specification
162Function `cell_spec` is introduced in version 0.6.0 of `kableExtra`. Unlike `column_spec` and `row_spec`, **this function is designed to be used before the data.frame gets into the `kable` function**. Comparing with figuring out a list of 2 dimentional index for targeted cells, this design is way easier to learn and use and it fits perfectly well with `dplyr`'s `mutate` and `summarize` functions. With this design, there are two things to be noted:
163* Since `cell_spec` generates raw `HTML` or `LaTeX` code, make sure you remember to put `escape = FALSE` in `kable`. At the same time, you have to escape special symbols including `%` manually by yourself
164* `cell_spec` needs a way to know whether you want `html` or `latex`. You can specify it locally in function or globally via the `options(knitr.table.format = "latex")` method as suggested at the beginning. If you don't provide anything, this function will output as HTML by default.
165
166Currently, `cell_spec` supports features including bold, italic, monospace, text color, background color, align, font size & rotation angle. More features may be added in the future. Please see function documentations as reference.
167
168## Conditional logic
169It is very easy to use `cell_spec` with conditional logic. Here is an example.
170```{r, message=FALSE, warning=FALSE}
171library(dplyr)
172mtcars[1:10, 1:2] %>%
173 mutate(
174 car = row.names(.),
175 # You don't need format = "html" if you have ever defined options(knitr.table.format)
176 mpg = cell_spec(mpg, "html", color = ifelse(mpg > 20, "red", "blue")),
177 cyl = cell_spec(cyl, "html", color = "white", align = "c", angle = 45,
178 background = factor(cyl, c(4, 6, 8),
179 c("#666666", "#999999", "#BBBBBB")))
180 ) %>%
181 select(car, mpg, cyl) %>%
182 kable("html", escape = F) %>%
183 kable_styling("striped", full_width = F)
184```
185
186## Visualize data with Viridis Color
187This package also comes with a few helper functions, including `spec_color`, `spec_font_size` & `spec_angle`. These functions can rescale continuous variables to certain scales. For example, function `spec_color` would map a continuous variable to any [viridis color palettes](https://CRAN.R-project.org/package=viridisLite). It offers a very visually impactful representation in a tabular format.
188
189```{r}
190iris[1:10, ] %>%
191 mutate_if(is.numeric, function(x) {
192 cell_spec(x, "html", bold = T,
193 color = spec_color(x, end = 0.9),
194 font_size = spec_font_size(x))
195 }) %>%
196 mutate(Species = cell_spec(
197 Species, "html", color = "white", bold = T,
198 background = spec_color(1:10, end = 0.9, option = "A", direction = -1)
199 )) %>%
200 kable("html", escape = F, align = "c") %>%
201 kable_styling("striped", full_width = F)
202```
203
204In the example above, I'm using the `mutate` functions from `dplyr`. You don't have to use it. Base R solutions like `iris$Species <- cell_spec(iris$Species, color = "red")` also works.
205
206## Text Specification
207If you check the results of `cell_spec`, you will find that this function does nothing more than wrapping the text with appropriate HTML/LaTeX formatting syntax. The result of this function is just a vector of character strings. As a result, when you are writing a `rmarkdown` document or write some text in shiny apps, if you need extra markups other than **bold** or *italic*, you may use this function to `r text_spec("color", color = "red")`, `r text_spec("change font size ", font_size = 16)` or `r text_spec("rotate", angle = 30)` your text.
208
209An aliased function `text_spec` is also provided for a more literal writing experience. In HTML, there is no difference between these two functions.
210
211```{r}
212sometext <- strsplit(paste0(
213 "You can even try to make some crazy things like this paragraph. ",
214 "It may seem like a useless feature right now but it's so cool ",
215 "and nobody can resist. ;)"
216), " ")[[1]]
217text_formatted <- paste(
218 text_spec(sometext, "html", color = spec_color(1:length(sometext), end = 0.9),
219 font_size = spec_font_size(1:length(sometext), begin = 5, end = 20)),
220 collapse = " ")
221
222# To display the text, type `r text_formatted` outside of the chunk
223```
224`r text_formatted`
225
226## Tooltip
227It's very easy to add a tooltip to text via `cell_spec`. For example, `text_spec("tooltip", color = "red", tooltip = "Hello World")` will give you something like `r text_spec("Hover over me", color = "red", tooltip = "Hello World")` (you need to wait for a few seconds before your browser renders it).
228
229Note that the original browser-based tooltip is slow. If you want to have a faster response, you may want to initialize bootstrap's tooltip by putting the following HTML code on the page.
230```
231<script>
232$(document).ready(function(){
233 $('[data-toggle="tooltip"]').tooltip();
234});
235</script>
236```
237
238In a rmarkdown document, you can just drop it outside of any R chunks. Unfortunately however, for rmarkdown pages with a **floating TOC** (like this page), you can't use bootstrap tooltips because there is a conflict in namespace between Bootstrap and JQueryUI (tocify.js). As a result, I can't provide a live demo here. If you want to have a tooltip together with a floating TOC, you should use `popover` which has a very similar effect.
239
240
241
242## Popover Message
243The popover message looks very similar with tooltip but it can hold more contents. Unlike tooltip which can minimally work without you manually enable that module, you **have to** enable the `popover` module to get it work. The upper side is that there is no conflict between Bootstrap & JQueryUI this time, you can use it without any concern.
244
245```
246<script>
247$(document).ready(function(){
248 $('[data-toggle="popover"]').popover();
249});
250</script>
251```
252
253<script>
254$(document).ready(function(){
255 $('[data-toggle="popover"]').popover();
256});
257</script>
258
259```{r}
260popover_dt <- data.frame(
261 position = c("top", "bottom", "right", "left"),
262 stringsAsFactors = FALSE
263)
264popover_dt$`Hover over these items` <- cell_spec(
265 paste("Message on", popover_dt$position), # Cell texts
266 popover = spec_popover(
267 content = popover_dt$position,
268 title = NULL, # title will add a Title Panel on top
269 position = popover_dt$position
270 ))
271kable(popover_dt, "html", escape = FALSE) %>%
272 kable_styling("striped", full_width = FALSE)
273```
274
275## Links
276You can add links to text via `text_spec("Google", link = "https://google.com")`: `r text_spec("Google", link = "https://google.com")`. If you want your hover message to be more obvious, it might be a good idea to put a `#` (go back to the top of the page) or `javascript:void(0)` (literally do nothing) in the `link` option.
277`text_spec("Hover on me", link = "javascript:void(0)", popover = "Hello")`:
278`r text_spec("Hover on me", link = "javascript:void(0)", popover = "Hello")`
279
280## Integration with `formattable`
281You can combine the good parts from `kableExtra` & `formattable` together into one piece. Read more at http://haozhu233.github.io/kableExtra/use_kableExtra_with_formattable.html
282```{r, message = FALSE, warning=FALSE}
283library(formattable)
284mtcars[1:5, 1:4] %>%
285 mutate(
286 car = row.names(.),
287 mpg = color_tile("white", "orange")(mpg),
288 cyl = cell_spec(cyl, "html", angle = (1:5)*60,
289 background = "red", color = "white", align = "center"),
290 disp = ifelse(disp > 200,
291 cell_spec(disp, "html", color = "red", bold = T),
292 cell_spec(disp, "html", color = "green", italic = T)),
293 hp = color_bar("lightgreen")(hp)
294 ) %>%
295 select(car, everything()) %>%
296 kable("html", escape = F) %>%
297 kable_styling("hover", full_width = F) %>%
298 column_spec(5, width = "3cm") %>%
299 add_header_above(c(" ", "Hello" = 2, "World" = 2))
300```
301
302
303# Grouped Columns / Rows
304## Add header rows to group columns
305Tables with multi-row headers can be very useful to demonstrate grouped data. To do that, you can pipe your kable object into `add_header_above()`. The header variable is supposed to be a named character with the names as new column names and values as column span. For your convenience, if column span equals to 1, you can ignore the `=1` part so the function below can be written as `add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)).
306```{r}
307kable(dt, "html") %>%
308 kable_styling("striped") %>%
309 add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
310```
311
312In fact, if you want to add another row of header on top, please feel free to do so.
313```{r}
314kable(dt, "html") %>%
315 kable_styling(c("striped", "bordered")) %>%
316 add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
317 add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
318 add_header_above(c(" ", "Group 6" = 6))
319```
320
321## Group rows via labeling
322Sometimes we want a few rows of the table being grouped together. They might be items under the same topic (e.g., animals in one species) or just different data groups for a categorical variable (e.g., age < 40, age > 40). With the new function `group_rows()` in `kableExtra`, this kind of task can be completed in one line. Please see the example below. Note that when you count for the start/end rows of the group, you don't need to count for the header rows nor other group label rows. You only need to think about the row numbers in the "original R dataframe".
323```{r}
324kable(mtcars[1:10, 1:6], "html", caption = "Group Rows") %>%
325 kable_styling("striped", full_width = F) %>%
326 group_rows("Group 1", 4, 7) %>%
327 group_rows("Group 2", 8, 10)
328```
329
330Another way to use `group_rows` is to provide an grouping index, similar with `add_header_above()`. This feature is only available in kableExtra > 0.5.2.
331```{r, eval = F}
332# Not evaluated. This example generates the same table as above.
333kable(mtcars[1:10, 1:6], "html", caption = "Group Rows") %>%
334 kable_styling("striped", full_width = F) %>%
335 group_rows(index = c(" " = 3, "Group 1" = 4, "Group 2" = 3))
336```
337
338For advanced users, you can even define your own css for the group labeling.
339```{r}
340kable(dt, "html") %>%
341 kable_styling("striped", full_width = F) %>%
342 group_rows("Group 1", 3, 5, label_row_css = "background-color: #666; color: #fff;")
343```
344
345## Row indentation
346Unlike `group_rows()`, which will insert a labeling row, sometimes we want to list a few sub groups under a total one. In that case, `add_indent()` is probably more apporiate.
347For advanced users, you can even define your own css for the group labeling.
348```{r}
349kable(dt, "html") %>%
350 kable_styling("striped", full_width = F) %>%
351 add_indent(c(1, 3, 5))
352```
353
354## Group rows via multi-row cell
355Function `group_rows` is great for showing simple structural information on rows but sometimes people may need to show structural information with multiple layers. When it happens, you may consider to use `collapse_rows` instead, which will put repeating cells in columns into multi-row cells.
356
357```{r}
358collapse_rows_dt <- data.frame(C1 = c(rep("a", 10), rep("b", 5)),
359 C2 = c(rep("c", 7), rep("d", 3), rep("c", 2), rep("d", 3)),
360 C3 = 1:15,
361 C4 = sample(c(0,1), 15, replace = TRUE))
362kable(collapse_rows_dt, "html", align = "c") %>%
363 kable_styling(full_width = F) %>%
364 column_spec(1, bold = T) %>%
365 collapse_rows(columns = 1:2)
366```
367
368# Table Footnote
369
370> Now it's recommended to use the new `footnote` function instead of `add_footnote` to make table footnotes.
371
372Documentations for `add_footnote` can be found [here](http://haozhu233.github.io/kableExtra/legacy_features#add_footnote).
373
374There are four notation systems in `footnote`, namely `general`, `number`, `alphabet` and `symbol`. The last three types of footnotes will be labeled with corresponding marks while `general` won't be labeled. You can pick any one of these systems or choose to display them all for fulfill the APA table footnotes requirements.
375```{r}
376kable(dt, "html", align = "c") %>%
377 kable_styling(full_width = F) %>%
378 footnote(general = "Here is a general comments of the table. ",
379 number = c("Footnote 1; ", "Footnote 2; "),
380 alphabet = c("Footnote A; ", "Footnote B; "),
381 symbol = c("Footnote Symbol 1; ", "Footnote Symbol 2")
382 )
383```
384
385You can also specify title for each category by using the `***_title` arguments. Default value for `general_title` is "Note: " and "" for the rest three. You can also change the order using `footnote_order`. You can even display footnote as chunk texts (default is as a list) using `footnote_as_chunk`.
386
387```{r}
388kable(dt, "html", align = "c") %>%
389 kable_styling(full_width = F) %>%
390 footnote(general = "Here is a general comments of the table. ",
391 number = c("Footnote 1; ", "Footnote 2; "),
392 alphabet = c("Footnote A; ", "Footnote B; "),
393 symbol = c("Footnote Symbol 1; ", "Footnote Symbol 2"),
394 general_title = "General: ", number_title = "Type I: ",
395 alphabet_title = "Type II: ", symbol_title = "Type III: ",
396 footnote_as_chunk = T
397 )
398```
399
400If you need to add footnote marks in table, you need to do it manually (no fancy) using `footnote_mark_***()`. Remember that similar with `cell_spec`, you need to tell this function whether you want it to do it in `HTML` (default) or `LaTeX`. You can set it for all using the `knitr.table.format` global option. ALso, if you have ever use `footnote_mark_***()`, you need to put `escape = F` in your `kable` function to avoid escaping of special characters.
401
402```{r}
403dt_footnote <- dt
404names(dt_footnote)[2] <- paste0(names(dt_footnote)[2],
405 footnote_marker_symbol(1))
406row.names(dt_footnote)[4] <- paste0(row.names(dt_footnote)[4],
407 footnote_marker_alphabet(1))
408kable(dt_footnote, "html", align = "c",
409 # Remember this escape = F
410 escape = F) %>%
411 kable_styling(full_width = F) %>%
412 footnote(alphabet = "Footnote A; ",
413 symbol = "Footnote Symbol 1; ",
414 alphabet_title = "Type II: ", symbol_title = "Type III: ",
415 footnote_as_chunk = T)
416```
417
418# HTML Only Features
419## Scroll box
420If you have a huge table and you don't want to reduce the font size to unreadable, you may want to put your HTML table in a scroll box, of which users can pick the part they like to read. Note that scroll box isn't printer friendly, so be aware of that when you use this feature.
421
422When you use `scroll_box`, you can specify either `height` or `width`. When you specify `height`, you will get a vertically scrollable box and vice versa. If you specify both, you will get a two-way scrollable box.
423
424```{r}
425kable(cbind(mtcars, mtcars), "html") %>%
426 kable_styling() %>%
427 scroll_box(width = "500px", height = "200px")
428```