首页 > 解决方案 > 在 R 控制台输出中右对齐字符串字符列

问题描述

我将文本片段分成三列。我想在 R 控制台中以KWIC 索引格式显示这三列,以便快速“视觉分析”。为此,第一列需要右对齐,中间的列居中,第三列左对齐。

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

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))

如果我只是打印数据,所有三列都是左对齐的,R 会在几行上显示索引线,所以它完全难以辨认。

data

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

Tibble 显示截图

我很感激有关如何实现这一点的任何提示。谢谢!

标签: rcorpus

解决方案


你可以试试这个:

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

编辑:

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

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...

推荐阅读