如何在 R knitr 中包装一个很长的段落 R 输出

How to wrap a really long paragraph R output in R knitr

我正在尝试使用 R Sweave/Knitr 将一个长段落放入 pdf 文件中。这一长段是从 excel 列之一中提取并粘贴在一起的。您可以将段落视为 1 x 1 对象:

cat("loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong")

目前,如果我将这一长段编译成 pdf:

 \documentclass{article}
 \begin{document}

 <<warning=FALSE, comment=NA, message=FALSE, echo=FALSE, tidy=TRUE,background="white">>=

 cat("looonno, oooooooooooooooooooooo, ooooooooooooooooooooooo, ooooooooooooooooooo, ooooonnnnnnnnnnnnnnnnnng")

 @

 \end{document}

输出不能换行文本本身,结果总是这样:

输出超出页面边缘。

我试过使用 option(width=60),但在这种情况下没有帮助,除非一个对象中有多个项目。

希望有人能提出让文本在页边距内换行的想法。

结合使用 strwrapwriteLines 和适当的 width 参数,您可以执行以下操作:

输出:

\documentclass{article}
\begin{document}

<<warning=FALSE, comment=NA, message=FALSE, echo=FALSE, tidy=TRUE,background="white">>=



x=paste0("looonno, oooooooooooooooooooooo, ooooooooooooooooooooooo, ooooooooooooooooooo, ooooonnnnnnnnnnnnnnnnnng, texttttttttttttttttttttttttt,
        goessssssssssssssss,onnnnnnnnnnn, foreverrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr, annnnnnnnnnnnnnnnnnnnnnnnnnd, everrrrrrrr")

cat("Before:","\n")

cat(x,"\n")

cat("After:","\n")

cat(writeLines(strwrap(x, width = 100)))


@

\end{document}