简体   繁体   中英

Adding line to .First() during package installation

I'm developing R packages for my company of not so tech savy employees.

To facilitate the life of the users I'm thinking of having a set of scripts at a global location that can get sourced at startup in order to update and load relevant packages.

My idea is to have a script for each custom package that only gets sourced if that particalar package is installed. For this to work I need to modify the .First() function when the user installs the different packages, such that after packages A is installed:

.First() <- function(){
    source('script_to_package_A')
}

and if package B is then installed:

.First() <- function(){
    source('script_to_package_A')
    source('script_to_package_B')
}

Thus i am interested to add a line inside the .Rprofile file if .First() is already defined and the line is not in there already or, if no .Rprofile exists, create it.

What would be the best way to achieve this?

best wishes Thomas

EDIT: Just to clarify - what I am looking for is a safe way to modify the .First() function that gets called during startup. That means that if a user already has defined a .First() function the additions will just be appended instead of replacing the old .First(). Preferably this addition to first will happen when a specific package is installed but this is not necessary. I'm fairly confident in what to add to the .First() function so this is not in question.

I suspect that the easiest way to get what you want is to have a single package installed on all machines. If you can alter the .First function on everyones machine, then you can install a package.

Your .First function would be:

.First() <- function(){
    library(mypkg)
    run_mypkg_fun()
    ##Could also check for package updates
    ##update.packages("mypkg"...)
}

The function run_mypkg_fun can do all the checks you want, including:

  • installing packages
  • running different functions conditional on what's installed.

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