How can I install packages in knitr?

一曲冷凌霜 提交于 2020-05-15 01:42:16

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/30674311/how-can-i-install-packages-in-knitr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!