Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

centering the table generated by kable function of knitr package

Tags:

centering

r

knitr

I am using the kable() function of knitr package to produce a nice book quality table in a pdf document. The output is as below where the table is placed on the left. enter image description here

I want to place the table at the center as below. enter image description here

I would appreciate if anyone can give some advice. I know I can do it using xtable. Is there any way I can do it directly using kable?

The complete reproducible knitr code (.Rnw file) is as below;

\documentclass{article}
\usepackage{booktabs}

\begin{document}

<<results='asis'>>=
library(knitr)
kable(head(women), format='latex', booktabs=TRUE)
@

\end{document}
like image 705
Mahbubul Majumder Avatar asked Oct 28 '15 20:10

Mahbubul Majumder


People also ask

What package is Kable in R?

The kableExtra package (Zhu 2021) is designed to extend the basic functionality of tables produced using knitr::kable() (see Section 10.1).

What does the Kable function do in R?

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.

How do I center a figure in R markdown?

Centering Images You can use the knitr include_graphics() function along with the fig. align='center' chunk option. This technique has the benefit of working for both HTML and LaTeX output. You can add CSS styles that center the image (note that this technique works only for HTML output).

What is knitr package?

The R package knitr is a general-purpose literate programming engine, with lightweight API's designed to give users full control of the output without heavy coding work. It combines many features into one package with slight tweaks motivated from my everyday use of Sweave.


1 Answers

With kableExtra, you can set the alignment by using:

kable(head(women), "latex", booktabs = T) %>%
  kable_styling(position = "center")

http://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

like image 65
Hao Avatar answered Oct 29 '22 06:10

Hao