Abstract
I give a walkthrough of a bash script that installs all of the R packages required by an R program (e.g., Shiny app, R file, R markdown file). This is useful for speeding up the workflow of adding a new Shiny app to a server.
Why do we need a script?
As explained in Dean Attali’s excellent post on how to setup an RStudio
and Shiny server,
you can install an R package (for example ‘mypackage’) for
everyone on a server at the command line with:
sudo su - -c "R -q -e "install.packages('mypackage', repos='http://cran.rstudio.com/')""
Repeating this long command once or twice is fine, but if you have an app that
requires several R packages such as:
# Dean Attali
# November 21 2014
# This is the server portion of a shiny app shows cancer data in the United
# States
source("helpers.R") # have the helper functions avaiable
library(shiny)
library(magrittr)
library(plyr)
library(dplyr)
library(tidyr)
library(ggplot2)
library(shinyjs)
# Get the raw data
cDatRaw getData()
...
then you want to automate the task of installing missing R packages.
The bash script
For the impatient among you, here is the entire script:
The one argument passed to the script is the location of the R file that
contains library(mypackage)
orrequire(mypackage)
commands (each on a separate line). The script will
determine whether or not each required
package is installed, and if it is not, the package will be
installed from CRAN.
The first few lines simply check to make sure that a single argument
is provided. If not, a usage reminder is echoed and the script exits.
Otherwise, the argument is saved so that it is available in the
variable $file
.
if [ $# -ne 1 ]; then
echo $0: usage: installAllRPackages.bash file
exit 1
fi
file=$1
The next set of lines creates three temporary files in the ‘~/tmp’ directory
(it must exist!) and sets a trap to delete them on exit.
tempfile() {
tempprefix=$(basename "$0")
mktemp ~/tmp/${tempprefix}.XXXXXX
}
TMP1=$(tempfile)
TMP2=$(tempfile)
TMP3=$(tempfile)
trap 'rm -f $TMP1 ...read more
Source:: r-bloggers.com