Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I install packages in knitr?

Tags:

markdown

r

knitr

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?

like image 830
maximusdooku Avatar asked Jun 05 '15 19:06

maximusdooku


2 Answers

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).

like image 151
Ben Bolker Avatar answered Sep 28 '22 17:09

Ben Bolker


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.

like image 27
mikeck Avatar answered Sep 28 '22 18:09

mikeck