abhisarihan
abhisarihan

Reputation: 261

Installing packages upon starting R session

I am fairly new to R programming. I am trying to customize my R setup so that when an R session is started a few packages are installed at the beginning. I know that there is a .First() function that I can write in the Rprofile.site file. However, upon adding my install package code inside the .First() function, the package does not get installed.

Furthermore, it seems to go into a loop of trying to create the package and it creates a lock file in the library folder in R. This causes my computer to really slow down (almost to the point where it is frozen) because it keeps trying to install that package.

Here is the code that I have added to the end of the Rprofile.site file.

.First <- function() {
  install.packages("customPackage.tar.gz", repos=NULL, type="source")
  cat("\nWelcome to R on ", date(), "\n") 
}

I even tried adding the install.packages line just by itself in the file (without having a .First() function) to no avail.

The customPackage.tar.gz refers to a package I built up using existing code that I have written up. Since this is a custom package, the repos is NULL. If I do not include this line in my .First() function and just run the command after launching the R session, the package gets installed just fine in the R/R-2.15.0/library folder.

There are several custom packages that I need to have installed upon the beginning of an R session, and that's why it is important that I add all these installation lines of code in the Rprofile.site file. Any ideas on how I can do this? Everywhere I have looked online on customizing the Rprofile.site file shows examples of just using libraries that already exist (For example, library(R2HTML)), but nothing for installing new libraries. Thanks for the help!

Edit: Thanks for the help guys! I actually do need to install these packages in multiple machines for each user and instead of having them manually install the package once, I figured it'll be good to do it in the site file. I tried Justin's suggestion for checking the package first and that worked! Thanks for the help again!

Upvotes: 2

Views: 1279

Answers (1)

Tyler Rinker
Tyler Rinker

Reputation: 109874

Unless you're switching from computer to computer you should have this package already in your library (that is once you install a package once it should always be there). Use installed.packages() [,1] or library() to see all packages in your library. If you see it there then use this:

.First <- function() {
  require(customPackage)
  cat("\nWelcome to R on ", date(), "\n") 
}

Upvotes: 7

Related Questions