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:

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)`

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With