37

I have some code that I run that includes this part:

if (!require("yaml")) {
  install.packages("yaml") 
  library("yaml")
}

When I run in it rstudio, everything runs seamlessly and there are no bugs. However, when I try running my code on the command line, I get this error:

$ Rscript.exe file.R
Loading required package: yaml
Installing package(s) into ‘/usr/lib/R/site-library’
(as ‘lib’ is unspecified)
Error in contrib.url(repos, type) :
  trying to use CRAN without setting a mirror
Calls: 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 ‘yaml’
Execution halted
kng
  • 651
  • 2
  • 7
  • 12

1 Answers1

54

RStudio sets a default repository when you call install.packages from within RStudio. When you run the script via the command line, you have to tell R which repository to use (or set a global default repository).

You can easily fix this problem by telling R to use your favorite repository.

For example, if you want to use RStudio's package repository, set repos="http://cran.rstudio.com/" inside the install.packages call.

if (!require("yaml")) {
  install.packages("yaml", repos="http://cran.rstudio.com/") 
  library("yaml")
}

This should work!

ialm
  • 8,510
  • 4
  • 36
  • 48
  • This then gives me the error: Loading required package: yaml Error in file(con, "r") : cannot open the connection Execution halted – kng Jul 17 '13 at 16:49
  • Do you know if the package was installed or not? Do you have other code in your script? Have you tried making a test script, say `test.R` with just the line `library("yaml")` to see if the package is being loaded correctly? – ialm Jul 17 '13 at 16:59
  • For some reason I thought that error was related to the same problem. It turns out I had used a suppress warnings wrapper earlier that was hiding the real issue. – kng Jul 17 '13 at 17:05