title: Check if R package is installed then load library
body: <p>Our R scripts are used on multiple users on multiple computers and hence there are deviations in which packages are installed on each computer. To ensure that each script works for all users I would like to define a function pkgLoad which will first test if the package is installed locally before loading the library with suppressed startup messages. Using <a href="https://stackoverflow.com/questions/9341635/how-can-i-check-for-installed-r-packages-before-running-install-packages">Check for installed packages before running install.packages()</a> as a guide, I tried</p>
  <pre><code> pkgLoad &lt;- function(x)
    {
      if (!require(x,character.only = TRUE))
      {
        install.packages(x,dep=TRUE, repos='http://star-www.st-andrews.ac.uk/cran/')
        if(!require(x,character.only = TRUE)) stop(&quot;Package not found&quot;)
      }
      #now load library and suppress warnings
      suppressPackageStartupMessages(library(x))
      library(x)
    }
  </code></pre>
  <p>When I try to load ggplot2 using pkgLoad(&quot;ggplot2&quot;) I get the following error message in my terminal</p>
  <blockquote>
  <p>Error in paste(&quot;package&quot;, package, sep = &quot;:&quot;) :
  object 'ggplot2' not found
  &gt; pkgLoad(&quot;ggplot2&quot;)
  Loading required package: ggplot2
  Error in library(x) : there is no package called ‘x’
  &gt; pkgLoad(&quot;ggplot2&quot;)
  Error in library(x) : there is no package called ‘x’</p>
  </blockquote>
  <p>Any why x changes from ggplot2 to plain old x?</p>