How to rename few column names as 2 lines

Hello Community,

We can rename the column using : colnames

colnames(df) = c("Car","Auto","Lorry")

Is there way to rename column names that are merged

colnames(df) = c("Car \n Jan 2018", "Auto", "Lorry \n Dec 2019")

Since Auto has no Month Year, it would be center aligned as we could do it in excel (attachment).


your question has to do with alignment and formatting. A data frame is just a data structure and has no formatting involved so I'm confused as to where you are getting your formatting from.

If you are outputting to HTML using Markdown, for example. You could replace your \n with the HTML tag for a line break:


df <- data.frame(A=1, B=2, C=3)
colnames(df) = c("Car\nJan 2018", "Auto", "Lorry\nDec 2019")

colnames(df) <- stringr::str_replace_all(colnames(df), "\\n", "<br>")
Jan 2018
Auto Lorry
Dec 2019
1 2 3

Created on 2019-02-13 by the reprex package (v0.2.1)

But if you are using some other formatting method or different output, you'll need a different method.

Thanks for your time.

Actually, this dataframe are fed to DT:: datatable to display in shiny.

So, I am currently passing the dataframe as

      DT::datatable(dataframe, options = list(initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'background-color': '#000', 'color': '#ffa500', 'font-size': '15px'});",
        "}"),lengthMenu = c(15, 20, 25), pageLength = 15, order = list(list(3,'desc')), columnDefs = list(list(className = 'dt-center', targets = 2:3), list(targets = 4,visible = FALSE)))) 

But it displays all column names in 1 line unlike how we want it to be displayed depending on the sceen size.

Is there a way we can adapt this DT functionality to display column header in such fashion ?

my example above that replaces the \n with <br> should work with Shiny as it's rendering in HTML. So <br> is all you need.

Here's an example from Stack Overflow

Thanks for suggestion but when I tried to incorporate it in header, it didnt break rather display
as character in column names :frowning:
But as a work around, I gave enough spaces to make it multi line.

oops, I didn't give you enough info.

In the Server side you're going to have to wrap your table in a datatable call with escape=FALSE:

    colnames(iris_data) <-
        c("one line",
    output$table <-
        renderDataTable(datatable(iris_data, escape = FALSE))

then in the UI it's:


Should give you something like:


Thanks a lot, you made it work....Actually, escape = F is what I had missed.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.