Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make R print printed column names vertically?

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

2 Answers

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

like image 71
lukeA Avatar answered Oct 18 '25 12:10

lukeA


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

like image 36
smci Avatar answered Oct 18 '25 11:10

smci