3

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

user9445536
  • 141
  • 1
  • 1
  • 9

1 Answers1

2

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

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • I’ve given up making this code robust: fixing it for arbitrary column names in the general case would make the code vastly more complicated: once would have to search for the actual column names inside `output[1L]`. But a simple `regexpr` search (or equivalent) is insufficient, since column names might contain each other (e.g. `colnames = c('foobar', 'foo')`). To find the correct positions, one would need to progressively truncate the prefix, or build a more complex regular expression to capture all column headers at once. – Konrad Rudolph Mar 05 '20 at 14:23