有没有办法加快R中的库加载?

Han*_*Sun 8 statistics performance r

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

虽然加载库并不需要花费太多时间,因为这个脚本可能会在命令行中执行数百万次,因此速度对我来说非常重要.

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

Dir*_*tel 9

不要重新启动 - 保持持久的R会话并向其发出请求.像Rserve这样的东西可以提供这一点,例如FastRWeb非常好地使用它 - 用于图表生成的毫秒往返.


cbe*_*ica 2

作为对@MikeDunlavey\'s 答案的补充:

\n

实际上,两者libraryrequire检查包是否已经加载。\n以下是microbenchmark我得到的一些计时:

\n
> microbenchmark (`!` (exists ("qplot")), \n                  `!` (existsFunction (\'qplot\')),  \n                  require (\'ggplot2\'),  \n                  library (\'ggplot2\'),   \n                  "package:ggplot2" %in% search ())\n\n## results reordered with descending median:\nUnit: microseconds\n                             expr     min       lq   median       uq     max\n3              library("ggplot2") 259.720 262.8700 266.3405 271.7285 448.749\n1        !existsFunction("qplot")  79.501  81.8770  83.7870  89.2965 114.182\n5              require("ggplot2")  12.556  14.3755  15.5125  16.1325  33.526\n4 "package:ggplot2" %in% search()   4.315   5.3225   6.0010   6.5475   9.201\n2                !exists("qplot")   3.370   4.4250   5.0300   6.2375  12.165\n
Run Code Online (Sandbox Code Playgroud)\n

作为比较,第一次加载:

\n
> system.time (library (ggplot2))\n   User      System verstrichen \n  0.284       0.016       0.300 \n
Run Code Online (Sandbox Code Playgroud)\n

(这是几秒钟!)

\n

最后,只要require"package:ggplot2" %in% search()之间不需要因子 3 = 10 \xce\xbcs,我就会选择require,否则就选择%in% search ()

\n