knitr: code in chunks gets wrapped unexpectedly

2020-04-21 05:21发布

问题:

In a beamer presentation using knit2pdf() and LaTeX, I sometimes find that code in chunks gets wrapped, even though I have set tidy=FALSE globally. For example, this chunk:

\item Fit this using \func{glm}:
<<berk-logit2, size='footnotesize'>>=
berkeley <- as.data.frame(UCBAdmissions)
berk.logit2 <- glm(Admit == "Admitted" ~ Dept + Gender,
                   data = berkeley, weights = Freq, family = "binomial")
@

Appears like this:

Note that all three lines are wrapped, as if in paragraph mode. The indented line in the code chunk uses spaces, not tabs.

When I look at the .tex file produced, nothing looks strange, that is the lines given to alltt look OK.

\item Fit this using \func{glm}:
\begin{knitrout}\footnotesize
\definecolor{shadecolor}{rgb}{1, 0.961, 0.933}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{berkeley} \hlkwb{<-} \hlkwd{as.data.frame}\hlstd{(UCBAdmissions)}
    \hlstd{berk.logit2} \hlkwb{<-} \hlkwd{glm}\hlstd{(Admit} \hlopt{==} \hlstr{"Admitted"} \hlopt{~} \hlstd{Dept} \hlopt{+} \hlstd{Gender,}
                       \hlkwc{data} \hlstd{= berkeley,} \hlkwc{weights} \hlstd{= Freq,} \hlkwc{family} \hlstd{=} \hlstr{"binomial"}\hlstd{)}
\end{alltt}
\end{kframe}
\end{knitrout}

Most other chunks produce the properly formatted output. E.g.,

<<mice-tab, size='footnotesize' >>=
data(Mice, package="vcdExtra")
mice.tab <- xtabs(Freq ~ litter + treatment + deaths, data=Mice)
ftable(litter + treatment ~ deaths, data=mice.tab)
@

gives:

What could be causing this? My setup is complex, so I don't have a MWE, but it would be helpful if I knew what to look for.

回答1:

You probably use the fragile frame option on slides where the wrapping works as expected.

Setting \begin{frame}[fragile] produces the correct result you showed for the mice-tab chunk:

\documentclass{beamer}
\begin{document}

<<echo = FALSE>>=
library(knitr)
opts_chunk$set(size = "footnotesize",
              eval = FALSE,
              tidy = FALSE)
@

\begin{frame}[fragile]
With fragile:
<<berk-logit2-fragile>>=
  berkeley <- as.data.frame(UCBAdmissions)
  berk.logit2 <- glm(Admit == "Admitted" ~ Dept + Gender,
                     data = berkeley, weights = Freq,
                     family = "binomial")
@

<<mice-tab-fragile>>=
data(Mice, package="vcdExtra")
mice.tab <- xtabs(Freq ~ litter + treatment + deaths, data=Mice)
ftable(litter + treatment ~ deaths, data=mice.tab)
@
\end{frame}

\begin{frame}
Not fragile:
<<berk-logit2>>=
  berkeley <- as.data.frame(UCBAdmissions)
  berk.logit2 <- glm(Admit == "Admitted" ~ Dept + Gender,
                     data = berkeley, weights = Freq,
                     family = "binomial")
@

<<mice-tab>>=
data(Mice, package="vcdExtra")
mice.tab <- xtabs(Freq ~ litter + treatment + deaths, data=Mice)
ftable(litter + treatment ~ deaths, data=mice.tab)
@
\end{frame}
\end{document}