How to use DT table in blogdown?
The DT::datatable
object often does not work appropriately in the blogdown
post. How to solve this issue?
It seems no good answers for this problem. DT
+ widgetframe
📦 is a potential solution. I will do some experiment in this post.
library(tidyverse)
library(DT)
# this is the package to solve above issue
library(widgetframe)
After loading the packages, let’s make some tables.
Knit File Format
Here I am using
Rmarkdown
rather than Rmd
!
Tibble
iris %>%
head(10) %>%
as_tibble()
## # A tibble: 10 × 5
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## <dbl> <dbl> <dbl> <dbl> <fct>
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
## 7 4.6 3.4 1.4 0.3 setosa
## 8 5 3.4 1.5 0.2 setosa
## 9 4.4 2.9 1.4 0.2 setosa
## 10 4.9 3.1 1.5 0.1 setosa
kableExtra
iris %>%
head(5) %>%
# this is a wrapping function for kbl in kableExtra
zetaEDA::print_kbl(
cap = "Test kableExtra"
)
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species |
---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | setosa |
4.9 | 3.0 | 1.4 | 0.2 | setosa |
4.7 | 3.2 | 1.3 | 0.2 | setosa |
4.6 | 3.1 | 1.5 | 0.2 | setosa |
5.0 | 3.6 | 1.4 | 0.2 | setosa |
gt
Note that gt
table has some displaying problem in Rmarkdown
, but it works fine in Rmd
. Really drives me crazy…
iris %>%
head(5) %>%
gt::gt()
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species |
---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | setosa |
4.9 | 3.0 | 1.4 | 0.2 | setosa |
4.7 | 3.2 | 1.3 | 0.2 | setosa |
4.6 | 3.1 | 1.5 | 0.2 | setosa |
5.0 | 3.6 | 1.4 | 0.2 | setosa |
DT
If you need to sort, search or add url link in the table, you will find the DT::datatable
super helpful.
However, usually
DT
table cannot appropriately display in blogdown environment.
For example,
iris %>%
head(5) %>%
DT::datatable(caption = "DOES NOT WORK Table")
We have to use widgetframe
package. See more details for this package here.
dt <- iris %>%
head(20) %>%
DT::datatable(
caption = "It Works Table",
rownames = FALSE,
selection = "none",
escape = FALSE,
class = "cell-border hover compact stripe",
fillContainer = T,
options = list(
dom = "frtip",
pageLength = 10,
scrollX = TRUE
)
)
widgetframe::frameWidget(dt, height = 300, width = "100%")
Now it works fine.
I am also curious about the bootstrap in DT::datatable
.
dt2 <- iris %>%
head(20) %>%
DT::datatable(
caption = "Bootstrap Table",
style = "bootstrap",
rownames = FALSE,
selection = "none",
escape = FALSE,
class = "cell-border hover compact stripe",
fillContainer = T,
options = list(
dom = "frtip",
pageLength = 10,
scrollX = TRUE
)
)
widgetframe::frameWidget(dt2, height = 300, width = "100%")
Well, DOES NOT WORK…
Summary
When using DT in blogdown post, do 2 step:
- Save
DT::datatable
to an object. - Use
widgetframe::frameWidget
.