Right-align R 控制台输出中的字符串字符列

Right-align string character column in R console output

我将文本片段分成三列。我想在 R 控制台的 KWIC concordance format 中显示这三列以便快速 "visual analysis"。为此,第一列需要right-aligned,中间居中,第三列left-aligned.

下面是一些示例数据来演示问题:

concordance1 <- c("Well it's not that easy as you can tell I was trying to work out how this", "is working", "but I can't say I understand yet")
concordance2 <- c("they've just", "been having", "more and more trouble")
concordance3 <- c(" sorry I wasn't really engaging Um I", "was thinking", "back to like youth club days...")
data <- as.data.frame(rbind(concordance1, concordance2, concordance3))

如果我只打印数据,所有三列都是 left-aligned 并且 R 会在几行中显示索引行,所以它完全难以辨认。

data

到目前为止,tibble 显示是我能找到的最好的。它将 table 的宽度调整到我的控制台显示(见屏幕截图),这是一个改进。这是一个开始,但为了快速分析这些索引,我需要能够 right-align tibble 显示中的第一列

Tibble display screenshot

对于如何实现这一目标的任何提示,我深表感谢。谢谢!

你可以试试这个:

print(mapply(format, data, justify=c("right", "centre", "left")), quote=F)

编辑:

要left-truncate第一列达到指定的最大宽度,您可以将其包装在一个函数中,如下所示:

format.kwic <- function(data, width=20) {
    trunc <- function(x, n=20) {
        x <- as.character(x)
        w <- nchar(x)
        ifelse(w > n, paste0("\U2026", substring(x, w-n, w)), x)
    }
    data[,1] <- trunc(data[,1], n=width)
    mapply(format, data, justify=c("right", "centre", "left"))
}
print(format.kwic(data), quote=F)

输出:

##      V1                     V2           V3                              
## [1,] … to work out how this  is working  but I can't say I understand yet
## [2,]           they've just been having  more and more trouble           
## [3,] … really engaging Um I was thinking back to like youth club days...