【发布时间】:2012-05-30 21:34:20
【问题描述】:
我有一个 Rscript 将在其第一行加载 ggplot2。
虽然加载一个库并不需要太多时间,因为这个脚本可能会在命令行中执行数百万次,所以速度对我来说真的很重要。
有没有办法加快这个加载过程?
【问题讨论】:
标签: performance r statistics
我有一个 Rscript 将在其第一行加载 ggplot2。
虽然加载一个库并不需要太多时间,因为这个脚本可能会在命令行中执行数百万次,所以速度对我来说真的很重要。
有没有办法加快这个加载过程?
【问题讨论】:
标签: performance r statistics
作为@MikeDunlavey's answer的补充:
其实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 和 "package:ggplot2" %in% search() 之间的因子 3 = 10 μs 不需要,我会选择 require,否则使用 %in% search ()。
【讨论】:
require(),而不会造成任何有意义的性能损失。
Dirk 说的,加上你可以使用exists 函数有条件地加载一个库,如
if ( ! exists( "some.function.defined.in.the.library" )){
library( the.library )
}
因此,如果您将其放入脚本中,您可以在同一个 R 会话中多次运行该脚本。
【讨论】: