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,438
  • 68
  • 55
  • 126
mcenno
  • 477
  • 5
  • 15

2 Answers2

2

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
  • 6,868
  • 1
  • 34
  • 57
jay.sf
  • 46,523
  • 6
  • 46
  • 87
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,098
  • 30
  • 32
  • 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