Search code examples
cssrknitrkablekableextra

knitr: exporting to html file but keeping style


I just found out the awesome knitr library in R, when viewing the result in the viewer it seems nice. However, when I write this to a html file the style is lost.

Code

library(knitr)
library(kableExtra)

some.table <- 
  data.frame (
    x = rep(1,3),
    y = rep(1,3)
  )

some.table

x <- kable(some.table, format = "html") %>%
  kable_styling(bootstrap_options = "striped", full_width = F, position = "left")

x

file <- file('test.html')
write(x, file)

Table in viewer
enter image description here

Table in browser
enter image description here

How can I export the table with the same style to a html file? Note that I have more data in the html file, so I should be able to append it.


Response to comment(s)
User: @Hao
When I use 'inspect element' in the Rstudio viewer, I can find this link to a stylesheet:
enter image description here
However the code herein seems to be huge as it is 582.298 characters.


Solution

  • The typical way of doing this is to put the code inside a rmarkdown document. It will handle everything for you.

    The only case you need to use the save_kable function kableExtra is that you have lots of tables and you want to save them as fragments. In that case, you can use

    library(kableExtra)
    cars %>%
      kable() %>%
      kable_styling() %>%
      save_kable()