【问题标题】:How to wrap text in R source with tidy and knitr如何使用 tidy 和 knitr 在 R 源代码中换行
【发布时间】:2013-02-15 19:18:22
【问题描述】:

我最近正在使用 knitr,虽然其中大部分方面都进行得相当顺利,但在完成的文档中包含 R 代码存在一个我还没有弄清楚的格式问题。我经常需要在我的 R 块中创建相对较长的文本字符串,例如xtable() 函数的标题。虽然 tidy 通常在包装 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}

【问题讨论】:

  • 任何切换到横向模式的机会都会为您提供额外的空间来容纳您的代码?这可能适用于中等长度的字符串。

标签: r knitr


【解决方案1】:

这是一个非常手动的解决方案,但我已经使用过。

您使用paste0 构建字符串,这让 tidy 有机会拆分它。

longstr <- paste0("This string will flow off the right side"," of the page, because tidy doesn't know how to wrap it.")

【讨论】:

  • 这可能是 R 方面的最佳解决方案;这似乎是一个简单的问题,但实际上它真的很难;另一种解决方案是使用 LaTeX 包列表,例如github.com/yihui/knitr-examples/blob/master/…
  • 我想我会在有时间的时候尝试列表,同时使用 paste0 () hack。感谢 Brian 和 Yihui。
  • 解决方案更新:我已经开始分块关闭 tidy,我知道它会遇到问题并手动格式化它们。这真的很好用。
【解决方案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."

不幸的是,我不知道这是否适用于 tidy,但它适用于 knitr 的 HTML 输出。

【讨论】:

  • 您可以使用cat(strwrap(longstr, 70), sep = '\n') 很好地打印它们。
【解决方案3】:

这个答案对派对来说有点晚了,但我发现即使我在早期的块中使用tidy.opts = list(width.cutoff = 60)(使用 RStudio 和 .Rnw 脚本),然后在每个块选项列表中我都包含 tidy = TRUE ,行的溢出仍然发生。我的溢出行位于创建 ggplot2 图的代码部分中。试错发现,如果我在行尾的+后加回车,就没有溢出问题了。 LaTeX 创建的 PDF 中不会显示额外的行。

【讨论】:

  • 你能澄清一下这是什么意思吗? "如果我在行尾的 + 后添加回车"
  • 键。
  • 我有同样的问题,但也有没有 ggplot 代码的行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-06
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 2018-09-07
相关资源
最近更新 更多