Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r check if package version is greater than x.y.z

Tags:

package

version

r

R packages have version numbers like 1.97.1. I can check what the version number is with

 packageVersion("data.table")

On my computer this returns 1.10.0.

What I want to do is check whether the data.table version is newer than say 1.9.7 because versions after 1.9.7 have a feature that my code needs. I've tried splitting the version into its constituent parts and evaluating them in different ways but I haven't figured out any robust way of doing this. Any advice greatly appreciated.

like image 285
JerryN Avatar asked Jan 05 '17 22:01

JerryN


People also ask

How do I check the package version in R?

1 Answer. You can use the packageVersion() function to print version information about the loaded packages. To print the version information about R, the OS and attached or loaded packages, use the sessionInfo() function.

How do I install a specific version of an R package?

To install a specific version of a package, we need to install a package called “remotes” and then load it from the library. Afterwards we can use install_version() by specifying the package name and version needed as shown below.

How do I install old packages in R?

Installing an older package from source If you know the URL to the package version you need to install, you can install it from source via install. packages() directed to that URL. If you don't know the URL, you can look for it in the CRAN Package Archive.


2 Answers

While utils::compareVersion() is fine, I would say that using packageVersion() with comparison operators (as indicated by @G5W in comments) is simpler:

packageVersion("data.table")
[1] ‘1.10.0’
> packageVersion("data.table")>"1.9.8"
[1] TRUE
> packageVersion("data.table")>"1.10.01"
[1] FALSE
> packageVersion("data.table")=="1.10.0"
[1] TRUE

This is illustrated in the examples for ?packageVersion; the ability to use comparison operators in this way is explicitly documented in ?package_version:

Functions numeric_version, package_version and R_system_version create a representation from such strings (if suitable) which allows for coercion and testing, combination, comparison, summaries (min/max), inclusion in data frames, subscripting, and printing. The classes can hold a vector of such representations.

like image 190
Ben Bolker Avatar answered Oct 04 '22 10:10

Ben Bolker


As suggested by Benjamin, the right tool is compareVersion:

version_above <- function(pkg, than) {
  as.logical(compareVersion(as.character(packageVersion(pkg)), than))
}

packageVersion("ggplot2")
# [1] '2.2.1'
version_above("ggplot2", "2.0.0")
# [1] TRUE
version_above("ggplot2", "3.0.0")
# [1] FALSE

Outcomes of compareVersion(a, b) are

  • -1 if a < b
  • 0 if a == b
  • 1 if a > b

Source:

?utils::compareVersion

like image 24
Fr. Avatar answered Oct 04 '22 11:10

Fr.