Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

underline column names in R

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

like image 491
user9445536 Avatar asked Dec 11 '25 22:12

user9445536


1 Answers

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

like image 169
Konrad Rudolph Avatar answered Dec 13 '25 15:12

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!