如何使用 Knitr pdf 输出将代码输出(文本)居中到页面中间?

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

我在编织成 PDF 时在 knitr 中的代码输出块中遇到中心对齐问题。

例如,如果我 运行 以下内容:

---
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)
```

我希望 summary(cars) 的所有输出都居中对齐。

由于您的输出是 class table 您可以使用以下解决方法(注意安装 kableExtraknitr 这两个库):

library(kableExtra)
library(knitr)

kable_styling(kable(summary(cars)), position = "center")

除此之外,我强烈推荐以下 PDF:https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

如果你想居中文本:

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