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?
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With