5.3 Control the width of text output
5.3 Control the width of text output
Sometimes the text output printed from R code may be too wide. If the output document has a fixed page width (e.g., PDF documents), the text output may exceed the page margins. See Figure 5.1 for an example.
The R global option width can be used to control the width of printed text output from some R functions, and you may try a smaller value if the default is too large. This option typically indicates a rough number of characters per line (except for East Asian languages). For example:
The output is too wide in this chunk:
```{r}
options(width = 300)
matrix(runif(100), ncol = 20)
The output of this chunk looks better:
options(width = 60)
matrix(runif(100), ncol = 20)
Not all R functions respect the `width` option. If this option does not work, your only choice may be to wrap the long lines of text. This is actually the default behavior of the `html_document` output format. If the HTML output format that you are using does not wrap the long lines, you may apply the CSS code below (see Section [7.1](/read/rmarkdown-cookbook-1.0-en/d068#html-css) for instructions):
pre code { white-space: pre-wrap; }
For PDF output, it is trickier to wrap the lines. One solution is to use the LaTeX package **listings** , which can be enabled via the Pandoc argument `--listings`. Then you have to set an option for this package, and the setup code can be included from an external LaTeX file (see Section [6.1](/read/rmarkdown-cookbook-1.0-en/d055#latex-preamble) for how), e.g.,
output: pdf_document: pandoc_args: --listings includes: in_header: preamble.tex
In `preamble.tex`, we set an option of the **listings** package:
\lstset{ breaklines=true } ```
If you do not like the appearance of code blocks with listings , you can set up other listings options in \lstset{}, e.g., you may change the font family with basicstyle=\ttfamily. You can find more information about this package in its documentation: https://ctan.org/pkg/listings.
Figure 5.1 shows the default pdf_document output that contains wide text, which exceeds the page margin. Figure 5.2 shows the PDF output when we use the listings package to wrap the text.

FIGURE 5.1: Normal text output that is too wide.

FIGURE 5.2: Text output wrapped with the listings package.
