title: Installing missing dependencies in an R package
body: <p>I'm distributing an R package that requires other packages. If any are missing I get (for example) the following error:</p>
  <blockquote>
  <p>library(whSample)
  Error: package or namespace load failed for ‘whSample’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
  there is no package called ‘dplyr’</p>
  </blockquote>
  <p>I have code to check and install dependencies in the whSample package, but R fails before it gets to it when it sees the <code>import(dplyr)</code> in NAMESPACE. Here's the first block of code when the package function is called:</p>
  <pre><code>  is_installed &lt;- function(mypkg) is.element(mypkg, installed.packages()[,1])
    whInstall &lt;- function(pkgNames){
      for(pkg in pkgNames){
        if(!is_installed(pkg)){
          install.packages(pkg, repos=&quot;http://lib.stat.cmu.edu/R/CRAN&quot;)
        }
        suppressMessages(suppressWarnings(
          library(pkg, character.only=T, quietly=T, verbose=F)))
      }
    }
    whInstall(c(&quot;magrittr&quot;,&quot;tools&quot;,&quot;purrr&quot;,&quot;openxlsx&quot;,&quot;data.table&quot;,&quot;dplyr&quot;,&quot;glue&quot;))```
  
  How can I get R to do these checks without running afoul of NAMESPACE?
  </code></pre>