简体   繁体   中英

Executing R scripts during package installation

Hopefully this has a straightforward answer, but I haven't been able to find it as yet.

I'm writing an R package, and when installed on Windows I want it to execute a script that searches for a system file ie list.files(path = "C:/Program Files/, ...) and then saves that path to the package directory as a text file for later reference.

I tried saving the script as src/install.libs.R but that stopped my package from building.

In case there is an alternative solution, I'm trying to save the path to the javaw.exe file that resides in the Program files directory (somewhere!), so that I can quickly call it in functions via system2() .

There is no hook in R for this: executing code during installation.

There is, however, an entire set of hooks for package load or attachment. I often use .onLoad() for this. See eg how RcppGSL remembers what linker and compiler flag to use -- from R/inline.R :

.pkgglobalenv <- new.env(parent=emptyenv())

.onLoad <- function(libname, pkgname) {

    if (.Platform$OS.type=="windows") {
        LIB_GSL <- Sys.getenv("LIB_GSL")
        gsl_cflags <- sprintf( "-I%s/include", LIB_GSL )
        gsl_libs   <- sprintf( "-L%s/lib -lgsl -lgslcblas", LIB_GSL )
    } else {
        gsl_cflags <- system( "gsl-config --cflags" , intern = TRUE )
        gsl_libs   <- system( "gsl-config --libs"   , intern = TRUE )
    }

    assign("gsl_cflags", gsl_cflags, envir=.pkgglobalenv)
    assign("gsl_libs", gsl_libs, envir=.pkgglobalenv)
}

Next in this file are how to use them:

LdFlags <- function(print = TRUE) {
    if (print) cat(.pkgglobalenv$gsl_libs) else .pkgglobalenv$gsl_libs
}

CFlags <- function(print = TRUE) {
    if (print) cat(.pkgglobalenv$gsl_cflags) else .pkgglobalenv$gsl_cflags
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM