underline column names in R

729 views Asked by At

How do you underline column names in R?

I tried saving a string and then using that with

library(crayon)

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

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

However string1 prints as "\033[4mhello\033[24m".

String2 prints as "\033[4mhello2\033[24m"

Please let me know how I can get the column names to be underlined.

I just want the column names to stand out, even changing the colour of the text when it prints to the console would be fine

1

There are 1 answers

1
Konrad Rudolph On

The default printing code for matrices and data.frames internally handles non-printable characters, and escapes them. That’s why the ANSI escape character code'\033' is escaped to `'\033', instead of being printed directly.

If you don’t want this, you will have to write your own print.data.frame function, similar to how tibble does this. Doing this properly requires a fair bit of logic (and thus, code). You could cheat, though:

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

This captures the standard print.data.frame output, and replaces the first row (= the column headers) with an underscore-formatted version.

(Note that if there is whitespace in your column names, the above code will fail.)