R: Wrap text in grid.table when a string exceeds a given length

I use grid.table in the gridExtra package to display a list of survey comments in a table format. When the comments (string variable) exceeds the given length, I want it to automatically insert the line break "\ 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))

I am open to using another table package if this function is available elsewhere.

+4
source share
1 answer

you can use strwrap,

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

All Articles