Created
May 2, 2024 15:00
-
-
Save srvanderplas/0bb8ab79946a879dc3eecdc7ac6438c6 to your computer and use it in GitHub Desktop.
Install all R packages loaded in any files within a folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This concatenates array values using a multi-character separater. | |
# https://dev.to/meleu/how-to-join-array-elements-in-a-bash-script-303a | |
joinByString() { | |
local separator="$1" | |
shift | |
local first="$1" | |
shift | |
printf "%s" "$first" "${@/#/$separator}" | |
} | |
# Get all packages loaded in qmd files in any subdirectory of the current directory | |
grep -r --include=*.qmd --include=*.R --include=*.Rmd "library(" | \ | |
# Split filename from line of the file, keep matching line | |
awk -F: '{print $2}' | \ | |
# Remove leading spaces and tabs | |
awk '{gsub(/^[ \t]+/,"", $0); print}' | \ | |
# Remove comments after the library() statement | |
awk -F# '{print $1}' | \ | |
# Remove any suppressXXX() commands, e.g. suppressPackageStartupMessages | |
sed 's/suppress.*\((.*)\)/\1/' | \ | |
# Remove library() from around package name | |
sed 's/library(\(.*\)).*/\1/' | \ | |
# Remove any quotes from around package name | |
sed -e 's/["()]//g' | \ | |
sed -e "s/'//g" | \ | |
# Remove any lines that have characters other than A-z,0-9,and . | |
grep -v -P '[^A-z0-9\.]' | \ | |
# Remove any lines that have \n in the middle of the package name | |
grep -v -P '\n' | \ | |
# Remove any lines that have brackets/_ | |
grep -v -P '[\[\]_]' | \ | |
# Remove any lines with non-ASCII characters | |
grep -v -P "[\x80-\xFF]" | \ | |
# Remove any lines starting with a number -- not valid R packages | |
grep -v "^[0-9]" | \ | |
# Sort packages and keep unique packages only | |
sort --uniq | \ | |
# Load into a BASH Array | |
readarray -t pkgs | |
# Create an install script and make it executable as R code | |
echo "install.packages(c('"$(joinByString "', '" ${pkgs[@]})"'), deps=T)" > pkg_install.R | |
sed -i '1 i #!/usr/bin/Rscript' pkg_install.R | |
chmod +x pkg_install.R | |
# Run install script and save output/errors to separate files | |
./pkg_install.R > pkg_install_output.text 2> pkg_install_errors.txt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment