Friday, January 15, 2016

Installing R packages for Rscript

Rscript usually fails if you try to load a package and the package is not installed. Merely adding a install.packages command at the top of your script doesn't make Rscript happy either because it doesn't know which CRAN mirror to get the packages from. Here's the right way to do it:

mirror.location <- "https://cran.mtu.edu"
library.path <- cat(.libPaths()) # this is the default installation path

get.necessary.packages <- function(){
 if (library(package = "reshape", logical.return = TRUE, lib.loc=library.path) == FALSE){
   install.packages("reshape", repos = mirror.location)
   library("reshape", lib.loc = library.path)
 }else{
   library("reshape", lib.loc = library.path)
 }
}

get.necessary.packages()

example <- matrix(data = c(1,1,1,1,2,2,2,2,3,3,3,3,1:12,1:12), ncol = 3)
example.melted <- melt(data = example)
example.casted <- cast(data = example.melted, formula = X2 ~ ., fun.aggregate = length)

cat('\n\n\n')
cat(example.casted[2,1])
cat('\n\n\n')


Another way is to add the following line to your ~/.Rprofile file:

local({r <- getOption("repos")
   r["CRAN"] <- "https://cran.mtu.edu"
   options(repos=r)
})
However this method may not be desirable if you are planning to distribute your code to laypeople who do not know what an Rprofile file is.
(Many thanks to RRR for helping me figure this out.)