R:将长文本换行,使每行长度相同

R: Wrap a long text so that each line has the same length

我正在尝试向绘图中添加长文本。目标是包装文本,使每行的长度相等。我查看了几个函数:strwrapformattext。但是其中 none 似乎可以选择使行相等。

我想解决方案应该在较短的行中的单词之间添加空格以弥补缺失的字符。也许有一个 function/argument 我错过了?

下面是我当前的换行(不等长):

txt <- paste(sample(LETTERS, 1000, replace=TRUE), collapse="")
txt <- strsplit(txt, "A|I|O|E|U")
txt <- paste(txt[[1]], collapse=" ")

plot(NA, xlim=c(0,1), ylim=c(0,1))
text(0.0, 0.5, paste(strwrap(txt, width=50), collapse="\n"), pos=4, cex=0.7)

这是实现它的一个技巧。

1) 定义一个函数,通过在单词之间添加空格将字符串扩展到所需的长度。

expandWidth <- function(str, width) {
  nmiss <- max(0, width-nchar(str))
  words <- unlist(strsplit(str, " "))
  ngaps <- length(words)-1
  addToAll   <- nmiss %/% ngaps
  addToStart <- nmiss %% ngaps
  nSpaces    <- rep(addToAll, ngaps)
  nSpaces[0:addToStart] <- nSpaces[0:addToStart] + 1
  spaces <- sapply(Map(rep, " ", nSpaces+1), paste, collapse="")
  paste(apply(rbind(c("", spaces), words), 2, paste, collapse=""), collapse="")
}

2) 处理文本。

txt <- paste(sample(LETTERS, 1000, replace=TRUE), collapse="")
txt <- strsplit(txt, "A|I|O|E|U")
txt <- paste(txt[[1]], collapse=" ")

# Add spaces
txt <- sapply(strwrap(txt, width=50), expandWidth, 50)

3) 使用字符大小相等的字体(如@rawr 所述)

plot(NA, xlim=c(0,1), ylim=c(0,1))
text(0.0, 0.5, paste(txt, collapse="\n"), pos=4, cex=0.7, family="mono")

结果: