R markdown:在评估之前从代码块访问变量

时间:2019-09-25 14:12:54

标签: r r-markdown knitr

我正在用rmd生成pdf报告。在一些图之前,我先写了一些关于它们的解释,但是尚未生成它们的代码和数据,在这些解释之后,它们位于代码块中。问题是,我需要访问在那些块之一中评估的R变量。 换句话说,我想在评估之前访问R变量。 下面是一个示例:

DataframeName <- transform(DataframeName,
    First_Date = dmy(First_Date)

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您的变量在文档中保持不变,建议您多次使用它们,将它们插入R options块中。

---
title: 'A nice title'
geometry: left=18mm, right=19mm, top=20mm, bottom=25mm
output:
  pdf_document:
    latex_engine: xelatex
header-includes:
    - \usepackage{multicol}
    - \usepackage{caption}
    - \usepackage{graphicx}
    - \usepackage{grffile}
    - \usepackage{float}
    - \usepackage{units}
    - \usepackage{environ}
    - \usepackage{setspace}
    - \usepackage{colortbl}
    - \usepackage{xcolor}
    - \usepackage{fancyhdr}
    - \usepackage{subfig}
    - \usepackage{longtable}
    - \usepackage{pdflscape}
    - \usepackage{indentfirst}
    - \usepackage{setspace}
tables: true
keep_tex: true
indent: true
fontsize: 12pt
---

```{r global_options, include=FALSE}

# packages
library(knitr)

knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
opts_knit$set(eval.after = "fig.cap")
knitr::opts_chunk$set(fig.pos = '!h')
options(knitr.kable.NA = '')

## preload your R variables here ##
variable_1 <- 2+2
variable_2 <- c("a", "b", "c")
variable_3 <- head(mtcars[, 2:5])
variable_4 <- plot(variable_3)
## preload your R variables here ##

```

The variable already runned/loaded in the ``R options`` chunk will be available at all time in the R Markdown document.

```{r}
print("Here is the value of the variable_1 :")
print(variable_1)
```