13

how do i display the line numbers of my code chunk with rmarkdown?

```{r}
   x <- 1:10
   y <- x^2
   plot(x,y)
```

and i would like the echo to be something like

 1  x <- 1:10
 2  y <- x^2
 3  plot(x,y)

Preferably like it is on Github...
Would be glad for any help

Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • This discussion looks relevant: https://github.com/yihui/knitr/issues/31 – Thomas Mar 11 '14 at 20:53
  • Thanks Thomas but unfortunatly this is not working properly i think. Looking at their ramnathv's [example](http://dl.dropboxusercontent.com/u/1161356/knitr-code-themes.pdf) you see, that there is a different indentation depending on the digits of each number: 1 is more left than 11... – Rentrop Mar 11 '14 at 23:58
  • 2
    @Thomas I believe this is not a duplicate: The other question only asks for `.Rnw`-files and thus LaTeX, but this question asks for a solution that also works for HTML. – jarauh Oct 28 '16 at 11:52
  • 1
    It is not a duplicate since Rnw documents and Rmd are very different. However, one answer under that post actually provided the correct solution: https://stackoverflow.com/a/53280591/559676 – Yihui Xie Oct 24 '19 at 19:47

2 Answers2

12

You can produce two code blocks: one for the presentation and another, hidden, for execution.

---
output:
  pdf_document:
     highlight: haddock
---

```{#numCode .R .numberLines}
x <- 1:10
y <- x^2
plot(x,y)
```

```{r results='asis', echo=FALSE}
x <- 1:10
y <- x^2
plot(x,y)
```

Note: If you replace pdf_document with html_document, you must provide the metadata "highlight".

shafee
  • 15,566
  • 3
  • 19
  • 47
Dan Boucher
  • 193
  • 2
  • 12
  • 1
    Where to find detailed documentation for syntax like `{#number .R .numberLines}` ? I was only aware of the style such as `{r eval=TRUE,...}`. – bruin Oct 11 '18 at 05:44
  • 1
    @bruin It is from Pandoc User's Guide: https://pandoc.org/MANUAL.html – lokheart Jan 10 '19 at 13:11
2

Use the chunk option attr.source='.numberLines':

```{r, attr.source='.numberLines'}
if (TRUE) {
  x <- 1:10
  x + 1
}
```

This works for HTML and PDF.

enter image description here

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225