【问题标题】:Why would an R package load random numbers?为什么 R 包会加载随机数?
【发布时间】:2018-09-13 10:04:04
【问题描述】:

最近,我在阅读caret 包的文档时注意到了这一点:

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

加载随机数的包有哪些可能的用例?这似乎与可重复研究的想法背道而驰,并且可能会干扰我自己对set.seed 的尝试。 (我已经开始将种子设置为更接近需要随机数生成的代码,正是因为我担心加载包的副作用。)

【问题讨论】:

    标签: r packages random-seed reproducible-research


    【解决方案1】:

    ggplot2 是执行此操作的包的一个示例,正如 Hadley Wickham 在对与 tidyverse 相关的 GitHub issue 的响应中提到的那样。

    当附加包裹时,会随机选择一个小费显示给用户(并且有一定的概率,不会显示小费)。如果我们检查它的.onAttach() 函数as it existed before January 2018,我们会看到它同时调用了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?"
      )
    }
    

    但是,自 been fixed 以来,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"))
      })
    }
    

    因此,包这样做可能有多种原因,尽管包作者可以通过多种方式防止这种情况给用户带来意想不到的后果。

    【讨论】:

    • 这是一个很好的例子。谢谢!我想知道是否有一种简单的方法可以生成包含某种随机过程的所有包的列表。
    • @SeanRaleigh 很高兴它有帮助。这听起来像是另一个在 SO 上发布的好问题
    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2021-09-10
    • 2017-07-15
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多