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

11
请给出一个在R Markdown中如何全局使用set.seed()的实际工作示例。我知道Yihui的文档基于这个错误报告, 但是当我将建议的选项放入设置块中如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)


1
我编辑了这个问题,使其不再是“参考请求”——否则它将被关闭。对我来说,这似乎是一个有效的问题。更多关于错误信息的信息可能会有所帮助。 - C8H10N4O2
你能再解释一下你的意思吗?如果你在第一个块中设置了种子,那么接下来的块将使用相同的初始种子值。 - Luke C
1
这是一个非常老的问题,而且你没有提供一个可重现的例子说明哪里出了问题。即使在中间块中使用 cache=TRUE,我也能得到可重现的结果。 - hrbrmstr
1
更新了。我应该把set.seed()放在设置块中吗? - ZacharyST
1
我知道这是一个老问题,但是文档对我来说不够清晰。我添加的信息有帮助吗? - ZacharyST
rand_seed is exported from knitr, so you probably need to run knitr::rand_seed instead of just rand_seed - David Rubinger
3个回答

2

我刚遇到同样的问题,我认为我已经解决了它...将种子放在第一个块内,并在knitr选项中设置cache = TRUE。希望能对你有所帮助!

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

[your code here]

1

你需要先加载knitr库。

library(knitr)
knitr::opts_chunk$set(tidy.opts=list(width.cutoff=80),tidy=TRUE)
knitr::opts_chunk$set(cache.extra = rand_seed)

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

你试过取消注释library(knitr)吗?


knitr::opts_chunks$set 会将该包加载到内存中(而不附加命名空间)。 - alan ocallaghan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接