如何在R Markdown中全局使用set.seed()?

时间:2017-12-20 01:07:35

标签: r markdown r-markdown

有人可以提供一个如何在R Markdown中全局使用set.seed()的工作示例吗?我基于Yihui's documentation了解this bug report,但当我将建议选项放在我的设置块中时,我收到一条错误消息knitr::opts_chunk$set(cache.extra = rand_seed)

我错过了什么?我目前在第一个需要它的代码块中只有一个随机种子,但是后来的块应该使用相同的种子。

[更新如下]

我的设置块:

```{r setup, include=FALSE}
#knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir = "/Users/Zack/Documents/UCLA/Courses/PP290_NetworkScience")
#library(knitr)
knitr::opts_chunk$set(tidy.opts=list(width.cutoff=80),tidy=TRUE)
knitr::opts_chunk$set(cache.extra = rand_seed)
```

错误:

Show in New WindowClear OutputExpand/Collapse Output
Error in knitr::opts_chunk$set(cache.extra = rand_seed) : 
  object 'rand_seed' not found

使用种子的块是:

```{r section1_3, error=TRUE, cache=FALSE, eval=TRUE, echo=TRUE}
set.seed(01082017)
# A binomial distribution is one that produces a series of numbers according to parameters you pass it.
# We can easily make it produces 1s and 0s and then populate an adjacency matrix with them.
# The last argument controls the ratio of 1s and 0s.  So, half the output will be 1, half will be 0, on average.
rbinom(1,1,.5)
rbinom(1,1,.5)
rbinom(1,1,.5)
rbinom(1,1,.5)
rbinom(1,1,.5)
```

目前,我已从我的R Markdown文件中删除了knitr::opts_chunk$set(cache.extra = rand_seed)

2 个答案:

答案 0 :(得分:0)

```{r setup, include=FALSE}
#knitr::opts_chunk$set(echo = TRUE) knitr::opts_knit$set(root.dir = 
"/Users/Zack/Documents/UCLA/Courses/PP290_NetworkScience")
#library(knitr) 
knitr::opts_chunk$set(tidy.opts=list(width.cutoff=80),tidy=TRUE) 
knitr::opts_chunk$set(cache.extra = rand_seed)
```

您尝试取消注释库(编织器)吗?

答案 1 :(得分:0)

我遇到了同样的问题,我想我已经解决了...将种子放入第一个块中,并在cache = TRUE选项中添加knitr。希望对您有帮助!

{r, set.seed(333)}
knitr::opts_chunk$set(cache = T)

[your code here]