4

I have a renderDataTable table in Rstudio Shiny that I build with some columns I want to have the header going multi-line, so that a long header string takes a small amount of horizontal space. E.g.:

My long header column is called a_very_long_header in my data.frame, and with the colnames trick below I can turn it into a-very-long-header, which then turns into an ugly multi-line header:

shinyServer(function(input, output, session) {
  output$dt <- renderDataTable({
  data =     data.frame(a_very_long_header=rnorm(10),a=rnorm(10),b=rnorm(10),c=rnorm(10),d=rnorm(10),e=rnorm(10),f=rnorm(10),g=rnorm(10),h=rnorm(10),i=rnorm(10),j=rnorm(10),k=rnorm(10),a1=rnorm(10),b1=rnorm(10),c1=rnorm(10),d1=rnorm(10),e1=rnorm(10),f1=rnorm(10),g1=rnorm(10),h1=rnorm(10),i1=rnorm(10),j1=rnorm(10),k1=rnorm(10))
  colnames(data) = c("a-very-long-header","a","b","c","d","e","f","g","h","u","j","k","a1","b1","c1","d1","e1","f1","g1","h1","u1","j1","k1")
    return(data)
   })
})


shinyUI(navbarPage("Foo", id="page", collapsable=TRUE, inverse=FALSE,
   tabPanel("Bar",
       dataTableOutput("dt")
      )
   )
)

enter image description here

Is there a more elegant way to turn a_very_long_header into a very long header so that it prints the header in multi-line?

jdharrison
  • 30,085
  • 4
  • 77
  • 89
719016
  • 9,922
  • 20
  • 85
  • 158
  • 1
    Just an update to jdharrison's post. You now need to add escape = FALSE in order to recognize HTML in DT table. [Shiny DT Documentation](https://rstudio.github.io/DT/) – Matt Jan 27 '17 at 13:58

1 Answers1

4

Use HTML

library(shiny)
runApp(list(
  server = function(input, output, session) {
  output$dt <- renderDataTable({
    data =     data.frame(a_very_long_header=rnorm(10),a=rnorm(10),b=rnorm(10),c=rnorm(10),d=rnorm(10),e=rnorm(10),f=rnorm(10),g=rnorm(10),h=rnorm(10),i=rnorm(10),j=rnorm(10),k=rnorm(10),a1=rnorm(10),b1=rnorm(10),c1=rnorm(10),d1=rnorm(10),e1=rnorm(10),f1=rnorm(10),g1=rnorm(10),h1=rnorm(10),i1=rnorm(10),j1=rnorm(10),k1=rnorm(10))
    colnames(data) = c("a very<br>long header","a","b","c","d","e","f","g","h","u","j","k","a1","b1","c1","d1","e1","f1","g1","h1","u1","j1","k1")
    return(data)
  })
}
, ui = navbarPage("Foo", id="page", collapsable=TRUE, inverse=FALSE,
                   tabPanel("Bar",
                            dataTableOutput("dt")
                   )
)
)
)

enter image description here

jdharrison
  • 30,085
  • 4
  • 77
  • 89
  • 1
    weird, in my case, if I do `colnames(data) = chartr("-","
    ",colnames(data))`, I can only see the first of the tokens displayed in the header...
    – 719016 Aug 11 '14 at 09:31