Skip to content

Instantly share code, notes, and snippets.

@padamson
Last active March 22, 2021 15:54
Show Gist options
  • Save padamson/b2eb520ac677c6809faf to your computer and use it in GitHub Desktop.
Save padamson/b2eb520ac677c6809faf to your computer and use it in GitHub Desktop.
Bash script to install all R packages required by an R program
#!/bin/bash
#Install any packages required by an R file that aren't already installed
if [ $# -ne 1 ]; then
echo $0: usage: installAllRPackages.bash file
exit 1
fi
file=$1
tempfile() {
tempprefix=$(basename "$0")
mktemp ~/tmp/${tempprefix}.XXXXXX
}
TMP1=$(tempfile)
TMP2=$(tempfile)
TMP3=$(tempfile)
trap 'rm -f $TMP1 $TMP2 $TMP3' EXIT
grep library $file >> $TMP1
grep require $file >> $TMP1
awk -F "[()]" '{ for (i=2; i<NF; i+=2) print $i }' $TMP1 >> $TMP2
while read p; do
truncate -s 0 $TMP3
sudo su - -c "R -q -e \"is.element('$p', installed.packages()[,1])\"" >> $TMP3
if grep -Fxq "[1] TRUE" $TMP3
then
echo "$p package already installed"
else
echo "installing $p package"
sudo su - -c "R -q -e \"install.packages('$p', repos='http://cran.rstudio.com/')\""
fi
done <$TMP2
@xavidp
Copy link

xavidp commented Jun 9, 2016

Hi Paul:

Do you mind if I include your bash script in an open source plugin to use R through web interfaces created with Tiki?
Re:

I couldn't see any explicit copyright notice, so that's why I'm asking (I would dual license with GPL and LGPL crediting you as the author, of course)

Thanks!

@padamson
Copy link
Author

padamson commented Oct 24, 2016

Feel free! You might also check out the comment on the related blog post.

@axd1967
Copy link

axd1967 commented Mar 21, 2017

Maybe you should consider adding the link to this gist inside the script itself - so one can find the source if needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment