0

As the title says, I'm attempting to knit an RMarkdown file but I am receiving the error:

Error in contrib.url(repos, "source) l trying to use CRAN without setting a mirror Calls: 
<Anonymous>... withvisible -> eval -> eval -> install.packages -> contrib.url Execution halted

The error is called on line 20 of my rmd file where I have my install.packages listed.

install.packages("ggplot2")
install.packages("zoo")

library(ggplot2)
library(zoo)
library(gridExtra)

I'm not quite sure what this would be, I tried taking the package chunk out to see if it would still read an error, but obviously, it errored out when I used one of the packages in my script.

Any suggestion would be appreciated, thank you.

Phil
  • 7,287
  • 3
  • 36
  • 66
  • 1
    Remove those lines. There's no need to reinstall packages you have installed each time you knit, and it makes no sense from markdown's standpoint. – Phil May 11 '20 at 20:47
  • The error suggests that your R script is not sourcing any `.Rprofile` or something that would tell R which mirror to use for installing packages. Pick a mirror and explicitly include it as `install.packages(c("ggplot2", "zoo"), repos="https://...")`, chosen from https://cran.r-project.org/mirrors.html – r2evans May 11 '20 at 20:51
  • @Phil, I think there are valid situations where the package needs to be installed each time. As an example, if I use a barebones docker (`rocker`) image, it might need to install some packages each time it is called. While I agree that this may not be the most desirable in the long-term, perhaps it is meant to be a throw-away no-deps rendering. – r2evans May 11 '20 at 20:53
  • 1
    @r2evans Fair enough, I can see that. – Phil May 11 '20 at 20:56

1 Answers1

0

One can use the installed.packages() function to determine whether a package needs to be installed during execution of an Rmd script.

For example, we'll check to see whether the zoo package is installed and install it if necessary, using the National Institute for Computational Sciences CRAN mirror (as noted by r2evans in the OP comments).

installedPackages <- installed.packages()[,1] 
if(!("zoo" %in% installedPackages)) install.packages("zoo",repos="https://mirrors.nics.utk.edu/cran/")
library(zoo)
Len Greski
  • 10,505
  • 2
  • 22
  • 33