R:当字符串超出设定长度时,在grid.table内换行文本

问题描述:

我使用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

可以使用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