代码之家  ›  专栏  ›  技术社区  ›  Peter

如何在rmarkdown for pdf文档中使用units包

  •  3
  • Peter  · 技术社区  · 6 年前

    我在一个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文档的图像: Image of rmarkdown pdf document:

    1 回复  |  直到 6 年前
        1
  •  2
  •   Katia    6 年前

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

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