5

Till now, I was using this chunk of code to load R packages and write .R files. But I am trying to use knitr

rm (list=ls(all=TRUE))
kpacks <- c('ggplot2','install_github','devtools','mapdata')
new.packs <- kpacks[!(kpacks %in% installed.packages()[,"Package"])]
if(length(new.packs)) install.packages(new.packs)
lapply(kpacks, require, character.only=T)
remove(kpacks, new.packs)
options(max.print=5.5E5)

But now, when I put this chunk of code in a Knitr document, I get this error:

Error in contrib.url(repos, "source") :
  trying to use CRAN without setting a mirror calls:......

How can I fix this?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
maximusdooku
  • 5,242
  • 10
  • 54
  • 94

2 Answers2

7

The narrow answer to your question is that you should set your repos option:

options(repos=c(CRAN="<something sensible near you>"))

You're hitting the problem because R's default behaviour when the repository option is initially unset is to query the user -- and it can't do that when you're running code non-interactively.

More broadly, I would question whether you want to include this sort of thing in your R code; under some circumstances it can be problematic.

  • what if the user doesn't have a network connection?
  • what if they are geographically very far from you so that your default repository setting doesn't make sense?
  • what if they don't feel like downloading and installing a (possibly large) package?

My preferred practice is to specify in the instructions for running the code that users should have packages X, Y, Z installed (and giving them example code to install them, in case they're inexperienced with R).

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Thank you. Makes sense. I do it so that users don't have to put their brains into loading packages. Internet isn't a problem. – maximusdooku Jun 05 '15 at 19:40
1

One way to avoid installing the packages is to do something like

if(!require(package.name))
  stop("you need to install package.name")

In your code chunk. Depending on your knitr document settings, this will generate the message in the document, in the console, or prevent the document from being knitted.

mikeck
  • 3,534
  • 1
  • 26
  • 39
  • 1
    this is already handled in the OP's code by checking the list of packages to install against `installed.packages()` ... – Ben Bolker Jun 05 '15 at 20:40
  • @Ben, that's true but my suggestion is more about communicating with the user rather than installing the packages. Using a series of `if(!require())` statements helps address the various points you listed when asking whether it is a good idea to have a `knitr` document try to force install R packages, while still keeping it simple for the user. – mikeck Jun 06 '15 at 19:57