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"))
})
}
因此,包这样做可能有多种原因,尽管包作者可以通过多种方式防止这种情况给用户带来意想不到的后果。