最近,我在阅读caret
包的文档时注意到以下内容:
另外,请注意,某些包在加载时(直接或通过命名空间)会加载随机数,并且这可能会影响[sic]可重复性。
什么是随机数加载包可能的使用场景?这似乎与可重复研究的思想相悖,并可能干扰我自己尝试set.seed
的努力。(我已经开始设置更接近需要生成随机数的代码的种子,因为我担心加载包的副作用。)
最近,我在阅读caret
包的文档时注意到以下内容:
另外,请注意,某些包在加载时(直接或通过命名空间)会加载随机数,并且这可能会影响[sic]可重复性。
什么是随机数加载包可能的使用场景?这似乎与可重复研究的思想相悖,并可能干扰我自己尝试set.seed
的努力。(我已经开始设置更接近需要生成随机数的代码的种子,因为我担心加载包的副作用。)
ggplot2
,正如Hadley Wickham在回应与tidyverse
有关的GitHub问题时提到的那样。.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?"
)
}
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"))
})
}
因此,导致软件包出现此类问题的原因可能有很多,但软件包作者可以采取措施防止这种情况对用户产生意外后果。