Require minimum version of R package

 ̄綄美尐妖づ 提交于 2019-11-30 11:05:29

I am not aware of such a function, but it should be quite easy to make one. You can base it on sessionInfo() or packageVersion(). After loading the packages required for the script, you can harvest the package numbers from there. A function that checks the version number would look like (in pseudo code, as I don't have time right now):

check_version = function(pkg_name, min_version) {
    cur_version = packageVersion(pkg_name)
    if(cur_version < min_version) stop(sprintf("Package %s needs a newer version, 
               found %s, need at least %s", pkg_name, cur_version, min_version))
}

Calling it would be like:

library(ggplot2)
check_version("ggplot2", "0.8-9")

You still need to parse the version numbers into something that allows the comparison cur_version < min_version, but the basic structure remains the same.

You could use packageVersion():

packageVersion("stats")
# [1] ‘2.14.1’

if(packageVersion("stats") < "2.15.0") {
    stop("Need to wait until package:stats 2.15 is released!")
}
# Error: Need to wait until package:stats 2.15 is released!

This works because packageVersion() returns an object of class package_version for which < behaves as we'd like it to (which < will not do when comparing two character strings using their lexicographical ordering).

After reading Paul's pseudocode, here's the function I've written.

use <- function(package, version=0, ...) {
  package <- as.character(substitute(package))
  library(package, ..., character.only=TRUE)
  pver <- packageVersion(package)
  if (compareVersion(as.character(pver), as.character(version)) < 0)
    stop("Version ", version, " of '", package, 
         "' required, but only ", pver, " is available")
  invisible(pver)
}

It functions basically the same as library(), but takes an extra version argument:

> use(plyr, 1.6)
> use(ggplot2, '0.9')
Error in use(ggplot2, "0.9") : 
  Version 0.9 of 'ggplot2' required, but only 0.8.9 is available
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!