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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With