代码之家  ›  专栏  ›  技术社区  ›  Sean Raleigh

哪些R包在附加时使用某种随机过程?[已关闭]

  •  1
  • Sean Raleigh  · 技术社区  · 7 年前

    这个问题的后续行动:

    Why would an R package load random numbers?

    我想知道是否有一种方法可以生成所有包的列表,这些包在附加时包含某种随机过程。

    1 回复  |  直到 7 年前
        1
  •  2
  •   duckmayr    7 年前

    我不知道有什么方法可以绝对肯定你列了一个详尽的清单。但是,我们可以检查您系统上安装的所有软件包,以查看它是否具有 .onAttach() .onLoad() 函数,如果是,它是否调用 runif() sample() ,我相信这将是最常见的情况下,一个包有某种随机过程时,附加。 1.

    check_packages <- function() {
        # get the names of all installed packages
        packs <- installed.packages()[ ,"Package"]
        # create an object to hold the names of packages that mess with the seed
        result <- character()
        # for each package
        for ( pack in packs ) {
            # see if it has an .onAttach or .onLoad function
            onattach <- try(getFromNamespace(".onAttach", pack), silent = TRUE)
            onload <- try(getFromNamespace(".onLoad", pack), silent = TRUE)
            # and if it does, check if it calls sample() or runif()
            if ( !inherits(onattach, "try-error") ) {
                if ( any(grepl("runif|sample", capture.output(onattach))) ) {
                    # if so, add that package to the result object
                    result <- c(result, pack)
                    next()
                }
            }
            if ( !inherits(onload, "try-error") ) {
                if ( any(grepl("runif|sample", capture.output(onload))) ) {
                    result <- c(result, pack)
                    next()
                }
            }
        }
        # and return the names of all packages that do this
        return(result)
    }
    

    对我来说,这导致了以下结果:

    [1] "forecast" "ggplot2" 
    

    正如我们在 my answer 对于您链接的问题, ggplot2 这样做是为了随机选择要向用户显示的提示。事实证明, forecast 执行相同的操作:

    > forecast:::.onAttach
    function (...) 
    {
        if (!interactive() || stats::runif(1) > 0.2) 
            return()
        tips <- c("Use suppressPackageStartupMessages() to eliminate package startup messages.", 
            "Stackoverflow is a great place to get help on R issues:\n  http://stackoverflow.com/tags/forecasting+r.", 
            "Crossvalidated is a great place to get help on forecasting issues:\n  http://stats.stackexchange.com/tags/forecasting.", 
            "Need help getting started? Try the online textbook FPP:\n  http://OTexts.org/fpp/", 
            "Want to stay up-to-date? Read the Hyndsight blog:\n  https://robjhyndman.com/hyndsight/", 
            "Want to meet other forecasters? Join the International Institute of Forecasters:\n  http://forecasters.org/")
        tip <- sample(tips, 1)
        msg <- paste("This is forecast", packageVersion("forecast"), 
            "\n ", tip)
        packageStartupMessage(msg)
    }
    <bytecode: 0x10e92738>
    <environment: namespace:forecast>
    


    1. 您可以在 grepl() 调用以添加调用伪随机数生成器的任意函数。
    推荐文章