【问题标题】:Is there a way to speed up the library loading in R?有没有办法加快 R 中的库加载速度?
【发布时间】:2012-05-30 21:34:20
【问题描述】:

我有一个 Rscript 将在其第一行加载 ggplot2

虽然加载一个库并不需要太多时间,因为这个脚本可能会在命令行中执行数百万次,所以速度对我来说真的很重要。

有没有办法加快这个加载过程?

【问题讨论】:

    标签: performance r statistics


    【解决方案1】:

    不要重新启动——保持一个持久的 R 会话,然后向它发出请求。像Rserve 这样的东西可以提供这个,例如FastRWeb 就很好地使用它——用毫秒来生成图表。

    【讨论】:

    • 这也是我的想法。我还要考虑控制 R 启动时加载的内容。如果您想提高效率,请控制配置文件,以便在启动时仅加载所需的库,在本例中包括 ggplot2。
    【解决方案2】:

    作为@MikeDunlavey's answer的补充:

    其实libraryrequire都检查包是否已经加载。 以下是我得到的microbenchmark 的一些时间安排:

    > microbenchmark (`!` (exists ("qplot")), 
                      `!` (existsFunction ('qplot')),  
                      require ('ggplot2'),  
                      library ('ggplot2'),   
                      "package:ggplot2" %in% search ())
    
    ## results reordered with descending median:
    Unit: microseconds
                                 expr     min       lq   median       uq     max
    3              library("ggplot2") 259.720 262.8700 266.3405 271.7285 448.749
    1        !existsFunction("qplot")  79.501  81.8770  83.7870  89.2965 114.182
    5              require("ggplot2")  12.556  14.3755  15.5125  16.1325  33.526
    4 "package:ggplot2" %in% search()   4.315   5.3225   6.0010   6.5475   9.201
    2                !exists("qplot")   3.370   4.4250   5.0300   6.2375  12.165
    

    为了比较,第一次加载:

    > system.time (library (ggplot2))
       User      System verstrichen 
      0.284       0.016       0.300 
    

    (这是几秒钟!)

    最后,只要 require"package:ggplot2" %in% search() 之间的因子 3 = 10 μs 不需要,我会选择 require,否则使用 %in% search ()

    【讨论】:

    • 干得好——我对“这应该得到基准测试”有同样的想法。感谢您这样做,为了清楚起见,我还将继续使用 require(),而不会造成任何有意义的性能损失。
    【解决方案3】:

    Dirk 说的,加上你可以使用exists 函数有条件地加载一个库,如

    if ( ! exists( "some.function.defined.in.the.library" )){
        library( the.library )
    }
    

    因此,如果您将其放入脚本中,您可以在同一个 R 会话中多次运行该脚本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 2022-01-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 2021-10-27
      • 1970-01-01
      相关资源
      最近更新 更多