6

I'm trying to rotate table column headers in RMarkdown. Since I don't have an understanding of CSS my attempts so far have proven to be futile.

So, how can I rotate the table column headers?

Here is a minimal example for a table in RMarkdown:

---
title: "Untitled"
output: 
  html_document:
    df_print: paged
    style: ./Table.css
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)
library(knitr)
```

<div class="table-header-rotated">

```{r test, result="asis"}

kable(head(mtcars), "html")
```
</div>

And the CSS file was made from the code presented here: https://codepen.io/chriscoyier/pen/Fapif

Can anyone give me a hint?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
mcenno
  • 509
  • 5
  • 18

2 Answers2

3

You could just use kable_styling() and row_spec() from kableExtra.

---
title: "Untitled"
output: 
  html_document:
    df_print: paged
    style: ./Table.css
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)
library(knitr)
```

<div class="table-header-rotated">

```{r test, result="asis"}
kable(head(mtcars), "html") %>%
kable_styling("striped", full_width = F) %>%
  row_spec(0, angle = -45)
```

yields: enter image description here

Hao
  • 7,476
  • 1
  • 38
  • 59
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • 2
    Thanks, but this doesn't work with bigger columns. Insert a `mtcars <- add_rownames(mtcars, "model")` before rendering the table and you will see that the rotation misplaces the column header. – mcenno Mar 07 '18 at 16:15
  • 1
    Also this does not make columns any narrower, if the width of the column was due to the long column header – Heikki Apr 15 '19 at 08:49
0

If you capture the html output you can use gsub to edit the appropriate lines to match the required class, div and span calls, and then use cat to return the edited output. I couldn't get the css to work exactly as shown on the link, but the approach below taken from here did rotate the labels:

First block prefaced with ```{css}


th.rotate {
  /* Something you can count on */
  height: 140px;
  white-space: nowrap;
}

th.rotate > div {
  transform: 
    /* Magic Numbers */
    translate(25px, 51px)
    /* 45 is really 360 - 45 */
    rotate(315deg);
  width: 30px;
}

th.rotate > div > span {
  border-bottom: 1px solid #ccc;
  padding: 5px 10px;
}


x <- kable(head(mtcars), "html")

x %>% 
  gsub('<th style="text-align:(left|center|right);"> ([^(>| )]+) </th>', 
       '<th class="rotate"><div><span>\\2</span></div></th>', x = .) %>% 
  cat(., sep = "\n")

JWilliman
  • 3,558
  • 32
  • 36
  • Thanks, this helped me! Just wanted to add that one needs `{r, results='asis'}` for the second chunk. – bug313 Sep 27 '21 at 09:56