如何使用带 rmarkdown 的单位包获取 pdf 文档

How to use units package with rmarkdown for pdf document

我在 rmarkdown 文档中使用 units 包进行 pdf 输出。 但是,这些单元既不能作为内联代码也不能作为代码块。是否可以使用带有 rmarkdown 的单位?

RStudio 中用于 rmarkdown 文档的 MWE:

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

rmarkdown pdf文档图片:

print(len * wid) 在常规 R 会话中将产生相同的结果。 units是特殊的对象,需要特殊的方法才能转换成字符串。 试试这个:

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