R中的下划线列名称

时间:2020-03-05 13:06:24

标签: r string dataframe crayon

您如何在R中的列名称下划线?

我尝试保存一个字符串,然后将其与

一起使用
library(crayon)

string1 <- underline("hello")
string2 <- underline("hello2")

colnames(table) <- c(string1, string2)

但是string1打印为"\033[4mhello\033[24m"

String2打印为"\033[4mhello2\033[24m"

请让我知道如何获得带下划线的列名。

我只希望列名突出,即使在打印到控制台时更改文本颜色也可以

1 个答案:

答案 0 :(得分:2)

矩阵和data.frames的默认打印代码在内部处理不可打印的字符,并对它们进行转义。这就是为什么ANSI转义字符代码'\033'转义为''\ 033'而不是直接打印的原因。

如果您不希望这样做,则必须编写自己的print.data.frame函数similar to how tibble does this。正确执行此操作需要相当多的逻辑(因此也需要代码)。但是,您可以作弊:

print.data.frame = function (x, ...) {
    output = capture.output(base::print.data.frame(x, ...))
    colnames = crayon::underline(colnames(x))
    regmatches(output[1L], gregexpr('\\S+', output[1L]))[[1L]] = colnames
    cat(output, sep = '\n')
}

捕获标准的print.data.frame输出,并用下划线格式的版本替换第一行(=列标题)。

(请注意,如果您的列名中包含空格,则上述代码将失败。)

相关问题