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

时间:2014-09-10 13:53:02

标签: r gridextra

我在gridExtra包中使用grid.table以表格格式显示调查注释列表。当comments(字符串变量)超过给定长度时,我希望它自动插入一个换行符" \ n"。

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))

如果此功能在其他地方可用,我愿意使用不同的表包。

1 个答案:

答案 0 :(得分:5)

你可以使用strwrap,

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