domingo, 19 de noviembre de 2017

Automatic output format in Rmarkdown

I am writing a Rmarkdown document with plenty of tables, and I want them in a decent format, e.g. kable. However I don't want to format them one by one. For example, I have created the following data frame in dplyr

data2 %>% group_by(uf) %>%
  summarise(n = n(), ) %>%
  arrange(desc(n))


One solution to the output format of this data frame would be to name it as an object in R, and then give it a format by using the kable function.

t1 <- data2 %>%
  group_by(uf) %>%
  summarise(n = n(), ) %>% arrange(desc(n))

knitr::kable(t1)

However, if your document has hundreds of these queries and you need a faster way to compile the document, while keeping the kable style automatically, avoiding giving a name to the data frame and even avoiding to call the kable function over that name, you can use the printr package. Just add the following piece of code inside a chunk at the beginning of your document and voilá.

library(printr)

Now, all of your data frames will have a decent style, and you do not need to worry about this issue. For example, I have knitted a presentation by using printr and the first code in this post, and this is the result:

3 comentarios:

  1. Another (more limited) option for HTML output is to set the `df_print` option to `kable`.
    http://rmarkdown.rstudio.com/html_document_format.html#data_frame_printing

    ResponderEliminar
  2. Very interesting. Thankyou. I usually do Rmd scripts with a lot of tables. I use kable. The problem for changing to printr is the tables captions. Is it possible to handle them with printr?

    ResponderEliminar
  3. So don't. Write something useful related to the post. The blog owner is giving you a link, so be kind enough to make a useful contribution to his blog. dofollow backlinks

    ResponderEliminar