Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically run a function when loading a R package

Tags:

r

I've got to create a very simple R package containing a function using RStudio. I want to give it to some students.

When my package is loaded I'd like it automatically start my function, without requiring the user to type its name. (The function waits for user input or could open a simple GUI)

How can I get it?

PD: I can't modify other people's .Rprofile, that's why I need a method to load the function automatically when the package is loaded.

like image 500
skan Avatar asked Jun 14 '16 20:06

skan


1 Answers

In case you want to run something when R starts:

Start RStudio, and run the following to create .Rprofile file in your home directory:

file.edit("~/.Rprofile")

Put the following function inside that file:

.First <- function(){
  cat("Hello!") # startup message

  require(data.table)   
  # or whatever packages you want to load 

  # or if you want to run a function in a file
if(file.exists("~/myfile.r")){
        source("~/myfile.r")
        myfunc()
    }

}

Save it. Done!

As to OP's edit

In case you want to run something when your package is loaded, you can use .onLoad and .onAttach functions. For example:

.onAttach <- function(libname, pkgname) {
  # to show a startup message
  packageStartupMessage("This is my package, enjoy it!")
}

.onLoad <- function(libname, pkgname) {
      # something to run
}
like image 82
989 Avatar answered Sep 21 '22 10:09

989