Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R package building: How to import a function from a package not on CRAN

Tags:

r

r-package

Problem

I am trying to import a function from a non-CRAN repo into my package. I know R searches CRAN for any package declared in the Imports: field of the DESCRIPTION file. Is there any way to, for example, import function from package 'notoncran', which is only on Github (or some other non-CRAN place).

Non-desirable workaround:

I've worked out a nondesirable workaround which would consist of bypassing the Imports: field completely by defining my function as something like:

myfun <- function(a,b){
    x <- require(notoncran)
    if(!x){
        print("installing notoncran because you don't have it...")
        devtools::install_github('repo/withpackage')
        require(notoncran)
    }
    ...
}

I don't like this idea out of principle as you are installing a/several packages(s) to some extent without the user's consent, from a potentially unregulated (theoretically dangerous) source. This also reduces the readability of the function to some extent by weighing the function down with administrative business. Lastly, this method would eventually require running require() or library(), throwing all of the package's functions into the user's namespace which is never ideal.

Thanks for any help on this.

like image 674
mc-sq Avatar asked May 04 '17 02:05

mc-sq


People also ask

Which function is import package in R?

import: An Import Mechanism for R The syntax allows for importing multiple objects from a package with a single command in an expressive way. The import package bridges some of the gap between using library (or require ) and direct (single-object) imports.

What is a base R package and CRAN package?

CRAN is a repository where the latest downloads of R (and legacy versions) are found in addition to source code for thousands of different user contributed R packages. Packages for R can be installed from the CRAN package repository using the install. packages function.


1 Answers

A super easy trick is to add a ‘remotes’ field into our DESCRIPTION file specifying the username/package_name target of our target package on Github.

Remotes:
    github::User/PackageNotOnCRAN
Import:
    PackageNotOnCRAN
Suggests:
    devtools,
    testthat

Not only will this work very well for files on github (github::), but works for git, bitbucket, local packages and more.

More information, how I figured it out.

like image 57
mc-sq Avatar answered Sep 29 '22 19:09

mc-sq