How to use set.seed() globally in R Markdown?

£可爱£侵袭症+ 提交于 2020-12-30 08:16:25

问题


Can someone please provide a working example of how to use set.seed() globally in R Markdown? I am aware of Yihui's documentation based on this bug report, but I get an error message when I put the suggested option in my setup chunk as knitr::opts_chunk$set(cache.extra = rand_seed).

What am I missing? I currently just have a random seed in the first code chunk that needs it, but later chunks should use the same seed.

[UPDATE BELOW]

My setup chunk:

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

Error:

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

The chunk that uses a seed is this:

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

For now, I have removed knitr::opts_chunk$set(cache.extra = rand_seed) from my R Markdown file.


回答1:


I've just had the same problem and I think I've fixed it... put the seed inside the first chunk and make cache = TRUE in the knitr options. I hope it helps you!

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

[your code here]



回答2:


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

Did you try to uncomment library(knitr)?



来源:https://stackoverflow.com/questions/47897435/how-to-use-set-seed-globally-in-r-markdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!