2014-09-10 37 views
4

我使用gridExtra包內的grid.table以表格格式顯示調查評論列表。當評論(字符串變量)超過給定的長度時,我希望它自動插入換行符「\ n」。R:當字符串超出設定長度時,在grid.table內換行文本

library(gridExtra) 
df<-data.frame(comments = c("Here is a short string", 
"Here is a long string that needs to be broken in half so that it doesn't run off the page", 
"Here is another short string")) 

grid.newpage() 
print(grid.table(df$comments)) 

如果此功能在其他位置可用,我願意使用不同的表格包。

+0

嘗試'RGraphics :: splitString' – baptiste 2014-09-10 14:14:04

+0

當我運行使用splitString只打印第一條評論。 print(grid.table(splitString(df $ comments))) – Braden 2014-09-10 14:39:23

+0

實際上,這是行不通的,因爲splitString試圖適應給定的視口,而grid.table調整視口以適應內容(惡性循環)。 – baptiste 2014-09-10 15:56:27

回答

4

可以使用strwrap,

d = sapply(lapply(df$comments, strwrap, width=50), paste, collapse="\n") 
grid.table(d) 
+0

作品......非常感謝。我早些時候遇到了strwrap,但在開始工作時遇到了麻煩。我沒有使用sapply和lapply命令。我真的需要花一些時間讓我的腦袋圍繞這些功能的工作方式。 – Braden 2014-09-11 15:36:42

+0

's/lapply(list,fun)'相當於'for(ii in 1:length(list))fun(list [[ii]]),並將結果收集到一個向量/列表中。 – baptiste 2014-09-11 15:49:06

+0

謝謝。這就說得通了。 – Braden 2014-09-11 17:59:35

相關問題