Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aligning all knitr tables in R markdown

I have an rmarkdown document with several tables which are currently being printed with kable(tbl, align = 'c'), but I am wondering if it is possible to set an option to default print all of the tables in the document with center alignment.

Something like

knitr::opts_chunk$set(fig.align = 'center')

except for centering table output rather than figure alignment.

like image 565
Steve Reno Avatar asked Dec 20 '17 14:12

Steve Reno


People also ask

How do you center a table in markdown?

Tables are center-aligned by default when they are included in a table environment (i.e., when the table has a caption). If you do not want to center a table, use the argument centering = FALSE.

How do I center align in R markdown?

To center an image using the knitr::include_graphics() function, include it within an R code chunk that has the fig. align='center' option (and perhaps other options to control width, etc.). For example: Be sure to include the echo = FALSE chunk option to prevent the chunk source code from being printed.

What is knitr :: Kable?

10.1 The function knitr::kable() The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.

What is knitr in Rmarkdown?

knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.


1 Answers

The knitr options such as fig.align control how the figure is displayed with respect to the document. A similar option for tables would control if the whole table was centered in the document or not.

To control the alignment of the contents within a table should be granular. You could make a wrapper function for kable that would provide the default options you want.

my_kable <- function(x, align = "c", ...) {
  knitr::kable(x, align = align, ...)
}

The my_kable function will use the the wanted align = 'c' as default and the use of the ... will let you pass any additional arguments needed for a specific table from my_kable to kntir::kable.

like image 54
Peter Avatar answered Oct 13 '22 14:10

Peter