vashfive
vashfive

Reputation: 21

Wrapping text in a tableGrob

I have a df with one column ("Reviewer Feedback") and two rows ("Reviewer 1" and "Reviewer 2"). I'm trying to wrap the text in the cells (the reviewer feedback) I keep getting an error: in gPathFromVector(names) : invalid grob name.

library(grid)
library(gridExtra)

text_cell <- function(text, width = unit(1, "cm")) {
  g <- textGrob(text, rot = 0, hjust = 0, vjust = 0.5)
  g$width <- width
  g
}

d4 <- data.frame(Reviewer_Feedback = c("This is a long text from reviewer 1 that needs to be wrapped",
                                       "This is a long text from reviewer 2 that needs to be wrapped"))

colnames(d4) <- "Reviewer Feedback"
rownames(d4) <- c("Reviewer 1", "Reviewer 2")

table_grobs <- tableGrob(d4, rows = NULL, theme = ttheme_default(core = list(fg_params = list(hjust =     0))))

# Set width of the column to 10 cm
table_grobs[["widths"]][1] <- unit(10, "cm")

# Wrap text in the cells. This is where I receive the error. 
for (i in 1:nrow(d4)) {
  cell_grob <- table_grobs[gPath(i, 1)]
  cell_grob <- text_cell(cell_grob$label, width = table_grobs[["widths"]][1])
  table_grobs[gPath(i, 1)] <- cell_grob
}

grid.draw(table_grobs)

Upvotes: 2

Views: 212

Answers (1)

Abdur Rohman
Abdur Rohman

Reputation: 2944

To wrap the text in the column, you can use strwrap and and create newlines with paste(...,collapse = '\n').

 # Change the width and the height as necessary

d4$wrapped_feedback <- sapply(d4$`Reviewer Feedback`, 
                       function(x) {x |> 
                         strwrap(width = 15) |> 
                         paste(collapse = "\n")})

ggsave("wrapped.pdf", tableGrob(d4), width = 8, height = 5)  

This resulted in the following wrapped.pdf

enter image description here

Upvotes: 1

Related Questions