mcenno
mcenno

Reputation: 561

RMarkdown: how to rotate table column headers

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?

Upvotes: 6

Views: 4572

Answers (2)

JWilliman
JWilliman

Reputation: 3883

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

Upvotes: 0

jay.sf
jay.sf

Reputation: 73342

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

Upvotes: 3

Related Questions