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:

    1. The output is too wide in this chunk:
    2. ```{r}
    3. options(width = 300)
    4. matrix(runif(100), ncol = 20)
    5. ```
    6. The output of this chunk looks better:
    7. ```{r}
    8. options(width = 60)
    9. matrix(runif(100), ncol = 20)
    10. ```

    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 for instructions):

    1. pre code {
    2. white-space: pre-wrap;
    3. }

    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 for how), e.g.,

    1. ---
    2. output:
    3. pdf_document:
    4. pandoc_args: --listings
    5. includes:
    6. in_header: preamble.tex
    7. ---

    In preamble.tex, we set an option of the listings package:

    1. \lstset{
    2. breaklines=true
    3. }

    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.

    Image 1: Normal text output that is too wide.

    FIGURE 5.1: Normal text output that is too wide.

    Image 2: Text output wrapped with the listings package.

    FIGURE 5.2: Text output wrapped with the listings package.