Skip to content

Instantly share code, notes, and snippets.

@josherrickson
Last active December 11, 2020 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josherrickson/ad5aae978240e23b21724e474673dbb5 to your computer and use it in GitHub Desktop.
Save josherrickson/ad5aae978240e23b21724e474673dbb5 to your computer and use it in GitHub Desktop.
#!/bin/bash
echo "i <- rownames(installed.packages())" > __tmp__.R
grep -oh --include=\*.{Rmd,R} -r * -e "\(library\|require\)([A-Za-z0-9.]\+)" | \
sed 's_library(_"_' | \
sed 's_require(_"_' | \
sed 's_)_",_' | sort | uniq | \
perl -p -e 's/\n/ /' | \
sed 's_^_new <- c(_' | \
sed 's_, *$_)_' \
>> __tmp__.R
echo >> __tmp__.R
echo "install.packages(new[!new %in% i])" >> __tmp__.R
# For debugging
#cat __tmp__.R
R --quiet -e "source('__tmp__.R')"
rm __tmp__.R
@josherrickson
Copy link
Author

When setting up a new computer, or installing a new version of R, you may need to install many packages from existing code. This can be somewhat frustrating if your library or require calls are spread about, leading you to run your build script repeatedly as you keep erroring.

This script examines all .R and .Rmd under the current directory (recursive), extracts any packages loaded via library or require, and installs them if they are not already installed.

@josherrickson
Copy link
Author

Some updates: Fix to missing newline (L14); reduce length of input string (L8).

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