问题
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 i.e. 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()
.
回答1:
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 e.g. 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
}
来源:https://stackoverflow.com/questions/32035151/executing-r-scripts-during-package-installation