如何在knitr中安装软件包? [英] How can I install packages in knitr?

查看:411
本文介绍了如何在knitr中安装软件包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我一直在使用这段代码来加载R包并写入.R文件.但是我正在尝试使用编织器

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)

但是现在,当我将这段代码放在Knitr文档中时,出现此错误:

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

我该如何解决?

推荐答案

这个问题的狭窄答案是您应该设置repos选项:

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

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

您遇到了这个问题,因为最初未设置存储库选项时R的默认行为是查询用户,而当您非交互地运行代码时,R不能这样做.

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.

更广泛地说,我会问您是否要在R代码中包括这种东西?在某些情况下可能会出现问题.

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.

  • 如果用户没有网络连接怎么办?
  • 如果它们在地理位置上离您很远,以至于默认存储库设置没有意义怎么办?
  • 如果他们不想下载并安装(可能是很大的)软件包,该怎么办?

我的首选做法是在运行代码的说明中指定用户应安装X,Y,Z软件包(并为他们提供示例代码来安装它们,以防他们不熟悉R).

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

这篇关于如何在knitr中安装软件包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆