2013-02-15 39 views
8

我最近和knitr一起工作,雖然大部分方面都很流暢,但在完成的文檔中包含R代碼時還存在一個格式問題,出。我經常需要在我的R塊中創建比較長的文本字符串,例如標題爲xtable()函數。雖然整理通常在包裝R代碼並將其保存在LaTeX中的陰影框中做得很好,但它不知道如何處理文本刺戳,因此它不包裹它們,而且它們流出右邊的頁。如何在R源文件中整理和整理文本

我會很滿意的解決方案,整理所有的工作。但是,我也會對我可以手動應用到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} 

回答

3

這是一個非常手動的解決方案,但我已經使用了。

您使用paste0建立了字符串,並給出了整齊分割它的機會。

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

這可能是R方面的最佳解決方案;這似乎是一個容易的問題,但實際上確實很難;另一種解決方案是使用LaTeX軟件包列表,例如https://github.com/yihui/knitr-examples/blob/master/066-listings-breaklines.Rnw – 2013-02-16 02:06:26

+0

我想我會在有空的時候嘗試列表,並在此期間使用paste0()。感謝Brian和Yihui。 – Gregory 2013-02-16 11:18:20

+1

解決方案更新:我已經開始只是在大塊的地方清理乾淨,我知道它會出現問題並手動格式化。這真的很好。 – Gregory 2013-02-22 22:24:14

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輸出效果非常好。

1

這個答案有點晚,但我發現即使在早期塊(使用RStudio和.Rnw腳本)中使用tidy.opts = list(width.cutoff = 60),然後在每個塊選項列表中包含tidy = TRUE,溢出線條仍然發生。我的溢出行在創建ggplot2圖的代碼段中。反覆試驗發現,如果我在行尾添加回車符,我沒有溢出問題。額外的行不顯示在LaTeX創建的PDF中。