Demo
kable
takes a data.frame
as input, and outputs the table into a markdown table
, which will get rendered into the appropriate output format.
For example, let’s say we wanted to share the first 6 rows of our gapminder data.
This gives us the following output
Afghanistan |
Asia |
1952 |
28.801 |
8425333 |
779.4453 |
Afghanistan |
Asia |
1957 |
30.332 |
9240934 |
820.8530 |
Afghanistan |
Asia |
1962 |
31.997 |
10267083 |
853.1007 |
Afghanistan |
Asia |
1967 |
34.020 |
11537966 |
836.1971 |
Afghanistan |
Asia |
1972 |
36.088 |
13079460 |
739.9811 |
Afghanistan |
Asia |
1977 |
38.438 |
14880372 |
786.1134 |
So how does that work? kable
prints out the following:
|country |continent | year| lifeExp| pop| gdpPercap|
|:-----------|:---------|----:|-------:|--------:|---------:|
|Afghanistan |Asia | 1952| 28.801| 8425333| 779.4453|
|Afghanistan |Asia | 1957| 30.332| 9240934| 820.8530|
|Afghanistan |Asia | 1962| 31.997| 10267083| 853.1007|
|Afghanistan |Asia | 1967| 34.020| 11537966| 836.1971|
|Afghanistan |Asia | 1972| 36.088| 13079460| 739.9811|
|Afghanistan |Asia | 1977| 38.438| 14880372| 786.1134|
And this then gets rendered as a table. This works for HTML, PDF, and word!
Adding captions to a table
Now, say that we wanted to include a caption? We use the caption
argument. This will also automatically number the table (woo! We’ll cover this later).
Table 9.1: The first 6 rows of the dataset, gapminder
Afghanistan |
Asia |
1952 |
28.801 |
8425333 |
779.4453 |
Afghanistan |
Asia |
1957 |
30.332 |
9240934 |
820.8530 |
Afghanistan |
Asia |
1962 |
31.997 |
10267083 |
853.1007 |
Afghanistan |
Asia |
1967 |
34.020 |
11537966 |
836.1971 |
Afghanistan |
Asia |
1972 |
36.088 |
13079460 |
739.9811 |
Afghanistan |
Asia |
1977 |
38.438 |
14880372 |
786.1134 |
Some other useful features of kable
include setting the rounding number, with the digits
option.
For example, we could present the first 2 digits of each number like so:
Table 9.2: The first 6 rows of the dataset, gapminder
Afghanistan |
Asia |
1952 |
28.80 |
8425333 |
779.45 |
Afghanistan |
Asia |
1957 |
30.33 |
9240934 |
820.85 |
Afghanistan |
Asia |
1962 |
32.00 |
10267083 |
853.10 |
Afghanistan |
Asia |
1967 |
34.02 |
11537966 |
836.20 |
Afghanistan |
Asia |
1972 |
36.09 |
13079460 |
739.98 |
Afghanistan |
Asia |
1977 |
38.44 |
14880372 |
786.11 |
There are other options that you can set in kable
, but for these options will get you through a large majority of what you need. For more information on what kable
can provide, see ?knitr::kable
.
There are many different ways to produce tables in R. We have chosen to show kable
today because kable is minimal, but powerful. If you want to extend kable
to do more, look at kableExtra, in particular the option kableExtra::kable_styling(latex_options = c("hold_position"))
.