Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display line numbers for code chunks in rmarkdown HTML and PDF

Tags:

r

r-markdown

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

like image 788
Rentrop Avatar asked Mar 11 '14 15:03

Rentrop


People also ask

How do you insert a line break in RMarkdown PDF?

To break a line in R Markdown and have it appear in your output, use two trailing spaces and then hit return .

How do I embed a code into chunks in R?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).

How do I use RMarkdown in PDF?

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want. When you click the button, rmarkdown will duplicate your text in the new file format.


2 Answers

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

like image 83
Dan Boucher Avatar answered Sep 28 '22 08:09

Dan Boucher


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

like image 26
Stéphane Laurent Avatar answered Sep 28 '22 06:09

Stéphane Laurent