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

时间:2018-05-11 20:21:55

标签: r pdf r-markdown units-of-measurement

我在rmarkdown文档中使用单位包进行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文件图片: Image of rmarkdown pdf document:

1 个答案:

答案 0 :(得分:2)

常规R会话中的

print(len * wid)将产生相同的结果。 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)`

enter image description here