首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用tableGrob在gridExtra中包装表中的文本

使用tableGrob在gridExtra中包装表中的文本
EN

Stack Overflow用户
提问于 2015-09-09 13:48:14
回答 2查看 2.9K关注 0票数 2

我有一系列的调查问题,我正在报告对一所学校、学校家庭和整个董事会的答复。有些问题是长的-我想做的是让文本在列结束时自动包装。现在我必须手动添加换行符。这有可能吗?我正在使用RVersion3.2.1和gridExtra_2.0.0。

一些代码:

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-09 14:01:27

您可以通过strwrap实现这一点。

代码语言:javascript
复制
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)

对我来说,这导致:

票数 7
EN

Stack Overflow用户

发布于 2015-09-09 14:07:48

另一个选项是Paul的"splitString“函数:

代码语言:javascript
复制
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'"))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32481347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档