2

Frequently I am running R scripts in bash mode. My script is called 981_conduct_regression.R. In this script, I call required packages with

if(!require(<package>)){
  install.packages("<package>")
  library(<package>)
}

Now when I call the script from bash mode (on Ubuntu 14.04), the script (shown below) fails to install the packages:

Loading required package: gridExtra
Installing package into ‘/home/michael/R/x86_64-pc-linux-gnu-library/3.1’
(as ‘lib’ is unspecified)
Error in contrib.url(repos, type) : 
  trying to use CRAN without setting a mirror
Calls: source ... eval -> eval -> install.packages -> grep -> contrib.url
In addition: Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘gridExtra’
Execution halted

What do I have to change for my idea to work?

Edit: Here is the .sh file:

#!/bin/bash

Rscript Code/981_conduct_regression.R
4
  • What is 981_conduct_regression.R? It is better if you keep things self-contained. Less confusing. Give a minimal named example script in your question, run it, then give the output. – Faheem Mitha Feb 7 '15 at 12:22
  • Thats the name of the RScript. – MERose Feb 7 '15 at 12:25
  • On a side note, if you put #!/usr/bin/env Rscript as the first line of your R file, and chmod u+x the file, you can just run it, rather than depending on a separate bash script to execute the intended script. stackoverflow.com/a/969680/1834057 – Nicholas Hamilton Apr 15 '15 at 3:49
  • Yes I know, thanks. But commonly, we pass arguments to the RScript. I don't do here because it's not necessary to replicate the problem. – MERose Apr 15 '15 at 7:08
3

You need to specify your CRAN mirror; interactively in R, run

chooseCRANmirror()

to pick an appropriate mirror, then

options("repos")

to see the resulting URL. You can add this permanently to your configuration in ~/.Rprofile:

local({r <- getOption("repos")
   r["CRAN"] <- "<URL from above goes here>" 
   options(repos=r)
})
2
  • please, should I add this chunk of code at the beginning of the R script, or within batch file? – maycca Jul 13 '20 at 15:08
  • You should add it to your ~/.Rprofile. – Stephen Kitt Jul 13 '20 at 16:42
0

Based on Stephen Kitt's suggestion, this resolved the problem:

~ $ cat .Rprofile 
local({r <- getOption("repos")
   r["CRAN"] <- "https://mirror.las.iastate.edu/CRAN/" 
   options(repos=r)
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.