5
votes

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.

1
As far as I know, Jupyter numbers cells in the order of execution, and does this for code cells only. So if two people try running the same notebook, their cell # would not necessarily agree. In RMarkdown, you can give names to cells, but it sounds like you know this already. Does this not solve your problem?kgolyaev
Hi, I can name cells, but i have so many it becomes tedious (yes, being lazy here). I am hoping Rmarkdown can automatically number the cells. We'd both be viewing the rendered html, not executing it. So rerunning and producing different cell numbers wouldnt be the issue hereSapsi

1 Answers

6
votes

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.