【问题标题】:sample function gives different result in console and in knitted document when seed is set设置种子时,示例函数在控制台和针织文档中给出不同的结果
【发布时间】:2019-05-23 04:18:58
【问题描述】:

我正在Rmarkdown 文件中创建一个文档,并将其编入 HTML 以提交文件。使用 sample 函数生成种子样本会在控制台和 knitted 文件中提供不同的结果。

我正在使用 R Studio 版本 1.0.153 和 R 3.6.0

编辑:我已将 R Studio 更新到版本 1.2.1335,但仍然遇到此问题

set.seed(1)
rnorm(1)
sample(1:10, 1)

在控制台和编织文件中,rnorm(1) 的值是相同的,但是,在控制台中,我看到我在控制台中采样了 6 个,在编织文档中采样了 7 个

【问题讨论】:

  • 它在两种情况下(控制台和针织文档)都为我生成了7
  • 你能把sessionInfo()的输出从编织和Rstudio控制台发布出来

标签: r rstudio r-markdown


【解决方案1】:

R 3.6.0 changed the sampling method。使用新方法(defaultRejection)我得到 7。使用旧方法我得到 6:

set.seed(1)
rnorm(1)
#> [1] -0.6264538
sample(1:10, 1)
#> [1] 7

set.seed(1, sample.kind = "Rounding")
#> Warning in set.seed(1, sample.kind = "Rounding"): non-uniform 'Rounding'
#> sampler used
rnorm(1)
#> [1] -0.6264538
sample(1:10, 1)
#> [1] 6

reprex package (v0.2.1) 于 2019 年 5 月 23 日创建

看来您在控制台中以某种方式设置了sample.kind = "Rounding"。您可以从RNGkind() 的输出中检查这一点。

【讨论】:

  • 非常感谢!这是完全正确的。 @Russ 提到的sessionInfo() 在控制台中显示了非默认选项(舍入),但在 knit 文档中没有任何内容。我可以通过设置 RNGkind(sample.kind = "Rejection") 将其改回来
猜你喜欢
  • 2023-02-08
  • 1970-01-01
  • 2016-04-13
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多