为什么一个R包会加载随机数?

5

最近,我在阅读caret包的文档时注意到以下内容:

另外,请注意,某些包在加载时(直接或通过命名空间)会加载随机数,并且这可能会影响[sic]可重复性。

什么是随机数加载包可能的使用场景?这似乎与可重复研究的思想相悖,并可能干扰我自己尝试set.seed的努力。(我已经开始设置更接近需要生成随机数的代码的种子,因为我担心加载包的副作用。)

1个回答

10
一个做到这一点的包的例子是ggplot2,正如Hadley Wickham在回应与tidyverse有关的GitHub问题时提到的那样。
当包被附加时,会随机选择一个提示显示给用户(并且有一定的概率不显示任何提示)。如果我们检查其2018年1月之前存在的.onAttach()函数,我们会看到它调用了runif()sample(),改变了种子。
.onAttach <- function(...) {
  if (!interactive() || stats::runif(1) > 0.1) return()

  tips <- c(
    "Need help? Try the ggplot2 mailing list: http://groups.google.com/group/ggplot2.",
    "Find out what's changed in ggplot2 at http://github.com/tidyverse/ggplot2/releases.",
    "Use suppressPackageStartupMessages() to eliminate package startup messages.",
    "Stackoverflow is a great place to get help: http://stackoverflow.com/tags/ggplot2.",
    "Need help getting started? Try the cookbook for R: http://www.cookbook-r.com/Graphs/",
    "Want to understand how all the pieces fit together? Buy the ggplot2 book: http://ggplot2.org/book/"
  )

  tip <- sample(tips, 1)
  packageStartupMessage(paste(strwrap(tip), collapse = "\n"))
}

release_questions <- function() {
  c(
    "Have you built the book?"
  )
}

然而,这个问题已经被修复,由Jim Hester提交了一个修复程序,使得在附加ggplot2后种子会被重置:
.onAttach <- function(...) {
  withr::with_preserve_seed({
    if (!interactive() || stats::runif(1) > 0.1) return()

    tips <- c(
      "Need help? Try the ggplot2 mailing list: http://groups.google.com/group/ggplot2.",
      "Find out what's changed in ggplot2 at http://github.com/tidyverse/ggplot2/releases.",
      "Use suppressPackageStartupMessages() to eliminate package startup messages.",
      "Stackoverflow is a great place to get help: http://stackoverflow.com/tags/ggplot2.",
      "Need help getting started? Try the cookbook for R: http://www.cookbook-r.com/Graphs/",
      "Want to understand how all the pieces fit together? Buy the ggplot2 book: http://ggplot2.org/book/"
      )

    tip <- sample(tips, 1)
    packageStartupMessage(paste(strwrap(tip), collapse = "\n"))
  })
}

因此,导致软件包出现此类问题的原因可能有很多,但软件包作者可以采取措施防止这种情况对用户产生意外后果。


这是一个很好的例子。谢谢!我想知道是否有一种简单的方法来生成所有包含某种随机过程的附加程序列表。 - Sean Raleigh
@SeanRaleigh 很高兴能帮到你。这听起来像是另一个很棒的问题可以在 SO 上发布。 - duckmayr
哪些R包在附加时使用某种随机过程? - Sean Raleigh

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