user2211671
user2211671

Reputation: 71

How to control output width when use knitr to compile to pdf?

using knitr to compile to a .Rnw document to a pdf, the width of output text in a chunk can not be resetted by out.width option. enter image description here

how to keep the output text in area with the background color?

Upvotes: 3

Views: 3329

Answers (1)

Yihui Xie
Yihui Xie

Reputation: 30184

The text output width in PDF is always a painful problem. It is not easy to make sure everything fits on a page. Two possible and general solutions (if you have to use LaTeX/PDF):

  1. make the white margin smaller in LaTeX, e.g.

    \usepackage{geometry}
    \geometry{verbose,tmargin=3cm,bmargin=3cm,lmargin=3cm,rmargin=3cm}
    
  2. make the text output narrower in R, e.g.

    options(width = 60)
    

Note these solutions are not guaranteed to work, because you can never be sure how wide the text output can be, and some output functions do not respect the width option. For example, it is almost impossible to make this work:

cat('This is a long long long long long long long long long long long long long long long long long long long long long long long long string. Haha.\n')

There are some LaTeX packages such as listings that can wrap the verbatim output, but that can also lead to ugly output. For example, if the natural output from R is this (suppose the two lines are too wide):

text output wrapped by R
and then wrapped by LaTeX

LaTeX wrapping can turn it to this:

text output wrapped
by R
and then wrapped by
LaTeX

For your specific application of showing a contingency table, my suggestion is to transpose the table (t(table(...))) and print it.

Upvotes: 4

Related Questions