我有一个将ggplot2
在第一行加载的 Rscript。
虽然加载库并不需要太多时间,因为这个脚本可能会在命令行中执行数百万次,所以速度对我来说真的很重要。
有没有办法加快这个加载过程?
我有一个将ggplot2
在第一行加载的 Rscript。
虽然加载库并不需要太多时间,因为这个脚本可能会在命令行中执行数百万次,所以速度对我来说真的很重要。
有没有办法加快这个加载过程?
Dirk 所说的,加上您可以使用该exists
函数有条件地加载库,如
if ( ! exists( "some.function.defined.in.the.library" )){
library( the.library )
}
因此,如果您将其放入脚本中,您可以在同一个 R 会话中多次运行该脚本。
作为@MikeDunlavey 回答的补充:
实际上,两者都library
检查require
包是否已经加载。以下是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
和之间的因子 3 = 10 μs,我会选择,否则使用."package:ggplot2" %in% search()
require
%in% search ()