Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use units package with rmarkdown for pdf document

I'm using the units package in an rmarkdown document for pdf output. However, the units do not function either in-line code or as code chunks. Is it possible to use units with rmarkdown?

MWE for rmarkdown document in RStudio:

---
title: "Units in R Markdown"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(units)
```

```{r define units, include=FALSE}
len <- set_units(5, mm)
wid <- set_units(10, mm)
```


In-line code: The area of the rectangle is `r len * wid`.

```{r echo = FALSE}

paste("The area of the rectangle is ", len * wid)

```

I'm expecting to see: The area of the rectangle is `r len * wid`mm^2

Image of rmarkdown pdf document: Image of rmarkdown pdf document:

like image 681
Peter Avatar asked Jan 24 '26 12:01

Peter


1 Answers

print(len * wid) in regular R session will produce the same result. units are special objects and need special methods to be converted to a string. Try this:

---
title: "Units in R Markdown"
date: "May 12, 2018"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(units)
```

```{r define units, include=FALSE}
len <- set_units(5, mm)
wid <- set_units(10, mm)
paste("The area of the rectangle is ", format(len * wid))
```


In-line code: The area of the rectangle is `r format(len * wid)`.

```{r echo = FALSE}

paste("The area of the rectangle is ", format(len * wid))

```

I'm expecting to see: The area of the rectangle is `r format(len * wid)`

enter image description here

like image 159
Katia Avatar answered Jan 27 '26 02:01

Katia