8

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.

skan
  • 7,423
  • 14
  • 59
  • 96
  • Have a look at `?Startup`. I think you will want to create a Rprofile to load the package and you might find that defining the function `.First` to run your function the best way to achieve your second aim. The exact details of how to do this is system dependent, but you should find all the information you need on that help page. – David_B Jun 14 '16 at 20:23
  • 1
    What does *automatically start my function* mean? – Rich Scriven Jun 14 '16 at 20:46
  • Imagine my package is called Regression, and inside I've created a function that opens a wxwidget interface (called GUI) to interact with the user, to input variable values. Automatically start my function means that when my package is started the user doesn't need to type and execute GUI because the package does it automatically, when you load the package everything runs automatically – skan Jun 14 '16 at 22:19
  • 3
    Use `.onAttach`. For example [here](https://github.com/Rdatatable/data.table/blob/d9cf539b0fda2197b3a1d3bd5a0b5180b036200f/R/onAttach.R). – eddi Jun 14 '16 at 22:30
  • One possible use case can be updating or loading global variables. – Naeem Khoshnevis Feb 07 '21 at 02:01

1 Answers1

9

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
}
989
  • 12,579
  • 5
  • 31
  • 53
  • 4
    Hm, in which file to put them? – untill May 09 '17 at 21:25
  • 3
    "By convention, .onLoad() and friends are usually saved in a file called zzz.R." http://r-pkgs.had.co.nz/r.html In practice they can go in any `*.R` file in the `R/` directory of your package. But it's a good idea to follow convention. – JD Long Dec 21 '18 at 21:09