gpt4 book ai didi

r - 为什么 R 包会加载随机数?

转载 作者:行者123 更新时间:2023-12-04 10:38:49 24 4
gpt4 key购买 nike

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

Also, please note that some packages load random numbers when loaded (directly or via namespace) and this may effect [sic] reproducibility.



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

最佳答案

执行此操作的包的一个示例是 ggplot2 ,正如 Hadley Wickham 所提到的回应 GitHub issue相关 tidyverse .

当包裹被附加时,会随机选择一个提示以显示给用户(并且有一定的概率,不显示提示)。如果我们检查它的 .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"))
})
}

因此,包执行此操作的原因可能有多种,尽管包作者可以通过多种方式防止这种情况给用户带来意外后果。

关于r - 为什么 R 包会加载随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com