| tags: [ R packages Rmarkdown ] categories: [Administration Coding ]
Creating 'pretty' tables using RMarkdown
Obviously R is capable of outputting data in various formats. The default method is functional but not ‘pretty’:
dt <- mtcars[1:5, 1:6]
dt
## mpg cyl disp hp drat wt
## Mazda RX4 21.0 6 160 110 3.90 2.620
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875
## Datsun 710 22.8 4 108 93 3.85 2.320
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215
## Hornet Sportabout 18.7 8 360 175 3.15 3.440
Now what happens if we use the kable() function from knitr:
kable(dt)
| mpg | cyl | disp | hp | drat | wt | |
|---|---|---|---|---|---|---|
| Mazda RX4 | 21.0 | 6 | 160 | 110 | 3.90 | 2.620 |
| Mazda RX4 Wag | 21.0 | 6 | 160 | 110 | 3.90 | 2.875 |
| Datsun 710 | 22.8 | 4 | 108 | 93 | 3.85 | 2.320 |
| Hornet 4 Drive | 21.4 | 6 | 258 | 110 | 3.08 | 3.215 |
| Hornet Sportabout | 18.7 | 8 | 360 | 175 | 3.15 | 3.440 |
That’s looking better but we can provide more parameters to tweak the output:
dt %>%
kable("html", caption = 'This is a table with a caption', digits = 2, align = 'c') %>%
kable_styling(font_size = 14)
| mpg | cyl | disp | hp | drat | wt | |
|---|---|---|---|---|---|---|
| Mazda RX4 | 21.0 | 6 | 160 | 110 | 3.90 | 2.62 |
| Mazda RX4 Wag | 21.0 | 6 | 160 | 110 | 3.90 | 2.88 |
| Datsun 710 | 22.8 | 4 | 108 | 93 | 3.85 | 2.32 |
| Hornet 4 Drive | 21.4 | 6 | 258 | 110 | 3.08 | 3.21 |
| Hornet Sportabout | 18.7 | 8 | 360 | 175 | 3.15 | 3.44 |
Interactive tables
I will cover interactive tables generated using htmltools and the DT package at a later date.
Note:
I’ve added custom CSS to format the tables:
<style type="text/css">
th {
background-color:#b1b1b1;
border-top:1px solid black;
border-bottom:1px solid black;
padding:12px;}
td{
background-color:#e7e7e7;
border-bottom:1px dotted black;
padding:2px;}
table{
border-collapse:collapse;
margin:10px 150px
border: 1px solid black;}
</style>