GregRousell
GregRousell

Reputation: 1077

Wrapping text in a table using tableGrob in gridExtra

I have a series of survey questions and am reporting on responses for a school, the family of schools and the entire board. Some of the questions are long - what I'd like to do is have the text automatically wrap when the column ends. Right now I have to manually add line breaks. Is this even possible? I'm using R version 3.2.1 and gridExtra_2.0.0.

Some code:

library(gridExtra)
library(grid)
library(ggplot2)

key <- c("I feel close to other parents with children the same age", "I am comfortable asking for advice about parenting", "I take time out to take care of my own health and well−being")
SCH <- c(20,30,40)
FOS <- c(25,35,56)
BOARD <- c(32,44,58)

d <- data.frame(key, SCH, FOS, BOARD)

row.names(d) <- d[,1]
d[,1] <- NULL

g <- tableGrob(d)

g$widths <- unit (c(0.4, 0.1,0.1,0.1),"npc")
grid.newpage()
grid.draw(g)

Upvotes: 2

Views: 3432

Answers (2)

Chris
Chris

Reputation: 1615

Another option is the "splitString" function by Paul Murrell:

splitString <- function(text) {
 strings <- strsplit(text, " ")[[1]]
 newstring <- strings[1]
 linewidth <- stringWidth(newstring)
 gapwidth <- stringWidth(" ")
 availwidth <-
     convertWidth(unit(1, "npc"),
                    "inches", valueOnly=TRUE)
 for (i in 2:length(strings)) {
     width <- stringWidth(strings[i])
     if (convertWidth(linewidth + gapwidth + width,
                        "inches", valueOnly=TRUE) <
            availwidth) {
         sep <- " "
         linewidth <- linewidth + gapwidth + width
         } else {
             sep <- "\n"
             linewidth <- width
             }
    newstring <- paste(newstring, strings[i], sep=sep)
     }
 newstring
}

library(grid)
pushViewport(viewport())

grid.text(splitString("There was once a very long string that had to take up the entire viewport and then some but luckily there was also a function called 'splitString'"))

Upvotes: 0

Rentrop
Rentrop

Reputation: 21497

You can achive this with strwrap

key <- c("I feel close to other parents with children the same age", "I am comfortable asking for advice about parenting", "I take time out to take care of my own health and well−being")

key_wraped <- strwrap(key, width = 30, simplify = FALSE) # modify 30 to your needs
key_new <- sapply(key_wraped, paste, collapse = "\n")

d <- data.frame(key_new, SCH, FOS, BOARD)

For me this results in: enter image description here

Upvotes: 8

Related Questions