Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 339
ZacharyST Avatar asked Dec 20 '17 01:12

ZacharyST


People also ask

Do you only need to set seed once in R?

So the short answer to the question is: if you want to set a seed to create a reproducible process then do what you have done and set the seed once; however, you should not set the seed before every random draw because that will start the pseudo-random process again from the beginning.

Why do we set seed in R?

The set. seed() function in R is used to create reproducible results when writing code that involves creating variables that take on random values. By using the set. seed() function, you guarantee that the same random values are produced each time you run the code.

What is knitr R Markdown?

RMarkdown is an extension to markdown which includes the ability to embed code chunks and several other extensions useful for writing technical reports. The rmarkdown package extends the knitr package to, in one step, allow conversion between an RMarkdown file (.Rmd) into PDF, HTML, word document, amongst others.


1 Answers

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]
like image 86
jgarces Avatar answered Sep 18 '22 20:09

jgarces