当前位置:  开发笔记 > 编程语言 > 正文

在R中对齐文本

如何解决《在R中对齐文本》经验,为你挑选了1个好方法。



1> pickle rick..:

好吧,如果没有内置方式,这对我的目的来说足够好.感谢上面关于如何使用html样式的评论.

justify <- function(string, width'), 
                    fill=c('random', 'right', 'left')) {
    strs <- strwrap(string, width=width)
    paste(fill_spaces(strs, width, match.arg(fill)), collapse="\n")
}

fill_spaces <- function(lines, width, fill) {
    tokens <- strsplit(lines, '\\s+')
    res <- lapply(head(tokens, -1L), function(x) {
        nspace <- length(x)-1L
        extra <- width - sum(nchar(x)) - nspace
        reps <- extra %/% nspace
        extra <- extra %% nspace
        times <- rep.int(if (reps>0) reps+1L else 1L, nspace)
        if (extra > 0) {
            if (fill=='right') times[1:extra] <- times[1:extra]+1L
            else if (fill=='left') 
                times[(nspace-extra+1L):nspace] <- times[(nspace-extra+1L):nspace]+1L
            else times[inds] <- times[(inds <- sample(nspace, extra))]+1L
        }
        spaces <- c('', unlist(lapply(times, formatC, x=' ', digits=NULL)))
        paste(c(rbind(spaces, x)), collapse='')
    })
    c(res, paste(tail(tokens, 1L)[[1]], collapse = ' '))
}

cat(justify(string, width=40))
# Out  of the night  that covers me, Black
# as  the pit from  pole to pole, I  thank
# whatever   gods    may    be   For    my
# unconquerable soul. In  the fell  clutch
# of  circumstance I have  not  winced nor
# cried  aloud. Under the  bludgeonings of
# chance My  head  is bloody, but unbow'd.
# Beyond this  place  of  wrath and  tears
# Looms but  the Horror of the  shade, And
# yet  the menace of the years  Finds  and
# shall  find me unafraid. It  matters not
# how strait  the  gate,  How charged with
# punishments the scroll,  I am the master
# of  my fate:  I  am  the  captain  of my
# soul.

推荐阅读
sx-March23
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有