Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbered Code Chunks in RMarkdown

Tags:

r

r-markdown

Is there an option I can provide to code chunks in RMarkdown so that it will have a cell number attached to the HTML output. Much like Jupyter has cell numbers.

I've seen some example with line numbering which is not what I want.

Using cell numbers is helpful when I'm discussing an RMarkdown HTML file over the phone with someone. I can ask him/her to see cell 23. I have a lot of R code, so providing section titles, while possible, is tedious.

like image 358
Sapsi Avatar asked Feb 21 '18 19:02

Sapsi


1 Answers

Here's a solution using only CSS. It relies on CSS counters: each new R chunk increments the counter (named counter-rchunks).

You can knit the following minimal Rmd file and get this result:

enter image description here

---
title: "Counter for chunks"
author: "Romain Lesur"
output: html_document
---

```{css, echo=FALSE}
body {
  counter-reset: counter-rchunks;
}

div.main-container {
  padding-left: 5em;
}

pre.r {
  counter-increment: counter-rchunks;
  position: relative;
  overflow: visible;
}

pre.r::before {
  content: 'In [' counter(counter-rchunks) ']: ';
  display: inline-block;
  position: absolute;
  left: -5em;
  color: rgb(48, 63, 159);
}
```

```{r cars}
summary(cars)
```

```{r head-cars}
head(cars)
```

You may have to adapt this solution to your HTML template.
You also can insert these CSS rules to a .css file and includes it in your html_document.

like image 174
RLesur Avatar answered Sep 24 '22 01:09

RLesur