Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

r - Numbered Code Chunks in RMarkdown

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...