3
votes

In .Rnw files producing a LaTeX beamer presentation, I find that occasionally knitr causes the code in a chunk to wrap, as if it is continuous text, even though the chunk option tidy=FALSE is in effect (I've set this as default).

Most code chunks are formatted correctly. Here are a couple of examples of chunks that get wrapped.

  It is often useful to plot the data for the binary distinction between $y_i = 0$
  vs. $y_i > 0 $ as in logistic regression models.

<<phd-zero, h=5, w=5, out.width='0.5\\textwidth', size='footnotesize' >>=
plot(factor(articles==0) ~ mentor, data=PhdPubs,
    ylevels=2:1, ylab="Zero articles",
    breaks=quantile(mentor, probs=seq(0,1,.2)), cex.lab=1.25)
@

Which prints like this:

enter image description here

Here is another example:

    For simplicity, we use all predictors for both the zero model
    and the non-zero model.

<<size='footnotesize', tidy=FALSE>>=
library(countreg)
phd.zip <- zeroinfl(articles ~ ., data=PhdPubs, dist="poisson")
phd.znb <- zeroinfl(articles ~ ., data=PhdPubs, dist="negbin")

phd.hp  <- hurdle(articles ~ ., data=PhdPubs, dist="poisson")
phd.hnb <- hurdle(articles ~ ., data=PhdPubs, dist="negbin")
@

This one appears like this:

enter image description here

(Note that both of these examples use model formulas, and in both outputs, the ~ character does not appear in the output. However, other cases using model formulas work as expected.)

As I mentioned, almost all other code chunks print normally, respecting the spacing in the source for the chunks. What could be causing this problem?

I have also checked whether there are extra spaces at the end of lines in the offending chunks, but there are not.

If it makes any difference, I compile the presentation using knitr::knit2pdf()

1

1 Answers

0
votes

This behavior arises when you forget to use the [fragile] option for the frame. Often this causes an error, but in this case it mysteriously causes the bad formatting observed.

This works:

\begin{frame}[fragile]
  \frametitle{Example: Phd Publications}
    For simplicity, we use all predictors for both the zero model
    and the non-zero model.

<<fit-models, size='footnotesize', tidy=FALSE>>=
library(countreg)
phd.zip <- zeroinfl(articles ~ ., data=PhdPubs, dist="poisson")
phd.znb <- zeroinfl(articles ~ ., data=PhdPubs, dist="negbin")

phd.hp  <- hurdle(articles ~ ., data=PhdPubs, dist="poisson")
phd.hnb <- hurdle(articles ~ ., data=PhdPubs, dist="negbin")
@
\end{frame}