Search code examples
ralignmentr-markdownmarkdowncenter

How to Centre code output (text) to the middle of a page using Knitr pdf output?


I am having a problem with center aligning in code output chunks in knitr when knitting to PDF.

For example, if I run the following:

---
title: "TRIAL"
output: pdf_document
header-includes:
   - \usepackage{sectsty}
   - \allsectionsfont{\color{cyan}}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

\setlength{\leftskip}{7cm} 

## R Markdown

\setlength{\leftskip}{0cm}
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. 

```{r cars}
options(width = 80)
summary(cars)
```

I would like all output of summary(cars) to be center aligned.


Solution

  • Due to the fact that your output is of class table you can use the following workaround (note to install the two libraries kableExtra and knitr):

    library(kableExtra)
    library(knitr)
    
    kable_styling(kable(summary(cars)), position = "center")
    

    enter image description here

    In addition to that I highly recommend the following PDF: https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

    If you want to center text:

    \begin{center}
     centered text
    \end{center}