forked from yihui/knitr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datatables.Rmd
44 lines (33 loc) · 1.3 KB
/
datatables.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!--
%\VignetteEngine{knitr::knitr}
%\VignetteIndexEntry{Display Tables with the DataTables Library}
-->
# jQuery DataTables
We can use the JavaScript library [`DataTables`](http://www.datatables.net) to generate enhanced tables in HTML. In the example below, we create a table for the `mtcars` data:
```{r cool, results='asis'}
library(knitr)
kable(mtcars, 'html', table.attr='id="mtcars_table"')
```
Note we assigned an `id` to the table, and next we use the `DataTables` library to tweak the table.
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#mtcars_table').dataTable();
} );
</script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#mtcars_table').dataTable();
} );
</script>
Since this is a Markdown vignette, we need to add the JavaScript libraries as well as some additional CSS files to the HTML header, and this can be done via:
```{r}
options(markdown.HTML.header = unlist(
sapply(system.file('misc', c('vignette.css', 'datatables.txt'), package = 'knitr'), readLines)
)
)
```
Two files `vignette.css` and `datatables.txt` under the `misc` directory of **knitr** were added to the HTML output.
By comparison, below is an ordinary table:
```{r boring, results='asis'}
kable(head(mtcars), 'html')
```