我最近和knitr合作,虽然大部分方面都很顺利,但是在完成的文档中包含R代码还有一个格式问题,我还没想到。我经常需要在我的R块中创建相对较长的文本字符串,例如xtable()
函数的标题。虽然整洁一般很好地包装R代码并将其保存在LaTeX的阴影框中,但它不知道如何处理文本蜇,因此它不包裹它们,并且它们从右边流出页。
我很满意一个整理所有工作的解决方案。但是,我也对我可以手动应用于Rnw源中的R块中的长字符串的解决方案感到满意。我只是不想编辑KnitR创建的tex文件。
以下是一个最小的工作示例。
\documentclass[12pt, english, oneside]{amsart}
\begin{document}
<<setup, include=FALSE, cache=FALSE, tidy=TRUE>>=
options(tidy=TRUE, width=50)
@
<<>>=
x <- c("This","will","wrap","nicely","because","tidy","knows","how","to","deal","with","it.","So","nice","how","it","stays","in","the","box.")
longstr <- "This string will flow off the right side of the page, because tidy doesn't know how to wrap it."
@
\end{document}
答案 0 :(得分:4)
这是一个非常手动的解决方案,但我已经使用过了。
使用paste0
构建字符串,这样就可以分割它。
longstr <- paste0("This string will flow off the right side"," of the page, because tidy doesn't know how to wrap it.")
答案 1 :(得分:2)
另一种解决方案是使用strwrap。
> longstr <- "This string will flow off the right side of the page, because tidy doesn't know how to wrap it."
> strwrap(longstr, 70)
[1] "This string will flow off the right side of the page, because tidy" "doesn't know how to wrap it."
> str(strwrap(longstr, 70))
chr [1:2] "This string will flow off the right side of the page, because tidy" "doesn't know how to wrap it."
不幸的是,我不知道这是否适用于整洁,但它与knitr的HTML输出效果非常好。
答案 2 :(得分:2)
这个答案对于派对来说有点晚了,但我发现即使我在早期的块中使用tidy.opts = list(width.cutoff = 60)
(使用RStudio和.Rnw脚本),然后在每个块选项列表中我都包含{ {1}},行的溢出仍然发生。我的溢出行是代码段,用于创建ggplot2图。试验和错误发现,如果我在行末尾的+后添加一个回车符,我没有溢出问题。额外的行不会出现在LaTeX创建的PDF中。