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 <- ""
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)
   library("reshape", lib.loc = library.path)


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)


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

local({r <- getOption("repos")
   r["CRAN"] <- ""
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.) 

No comments:

Post a Comment