4

I believe in meaningful variable names. Unfortunately this often means that there are huge white gaps when I look at a data.frame in the R console:

enter image description here

Is there a way to tell R to print the column names vertically, like this:

enter image description here

It doesn't need to be in the console, maybe it is possible to plot a table to PDF that way?


Executable code, provided by Ben Bolker:

sample.table <- data.frame(a.first.long.variable.name=rep(1,7),
                           another.long.variable.name=rep(1,7),
                           this.variable.name.is.even.longer.maybe=rep(1,7)
                           )
starball
  • 20,030
  • 7
  • 43
  • 238
  • 1
    Please provide your code as text so readers can copy and paste it into their R console. – G. Grothendieck Nov 22 '15 at 12:25
  • 3
    I guess you could render it as an HTML table and apply rotation via CSS. E.g. `library(DT); datatable(setNames(mtcars, sprintf('
    %s
    ', names(mtcars))), escape = F) ` (Maybe you can apply `formatStyle` to column headers, but I didn't see how)
    – lukeA Nov 22 '15 at 12:32
  • That's an idea, thanks @lukeA. –  Nov 23 '15 at 07:32
  • @lukeA do you mind making your comment as answer, can't get it to work... – zx8754 Oct 11 '17 at 12:10
  • @zx8754 Did you try it in the Browser or just in the RStudio Viewer? Still seems to work for me in a browser. – lukeA Oct 11 '17 at 14:33
  • @lukeA Yes, right, it works in a browser but not in a viewer. Please post as an answer. – zx8754 May 29 '18 at 08:44
  • @zx8754 yep, done. – lukeA May 29 '18 at 11:16

2 Answers2

5

As described in the comments, you may apply rotation via CSS:

library(DT)
df <- mtcars
names(df) <- sprintf('<div style="transform:rotate(-90deg);margin-top:30px;">%s</div>', names(df))
dt <- datatable(df, escape = FALSE)
htmlwidgets::saveWidget(dt, tf<-tempfile(fileext = ".html"))
shell.exec(tf)

This does not work in the RStudio Viewer, however it does work in the browser:

enter image description here

lukeA
  • 53,097
  • 5
  • 97
  • 100
1

Not without using a graphics device. A better and simpler workaround which works in a plain old console is: Print the transpose of the table, now column-names become row-names:

> t(sample.table)
                                        1 2 3 4 5 6 7
a.first.long.variable.name              1 1 1 1 1 1 1
another.long.variable.name              1 1 1 1 1 1 1
this.variable.name.is.even.longer.maybe 1 1 1 1 1 1 1

(To suppress the useless column-names you get by default, include sample.table <- data.frame(row.names=1:7, ... )

I do this all the time. Heatmaps, dendrograms, auto-named regression variables from expanding categoricals...

smci
  • 32,567
  • 20
  • 113
  • 146