Standardizing boilerplate R code: Using {pacman}, clearing the environment, and freeing memory
Using {pacman}
One of the package management tools in R is the {pacman} package((UMIN ni wordpress de hōmupēji o tachiageru (3) MySQL no shoki settei. Kiso Igaku Kyōiku Kenkyūkai Nōto. Accessed February 21, 2021. https://plaza.umin.ac.jp/kikkenlab/note/umin-wordpress-03/)). Instead of listing multiple install.packages() and library() calls, you can write it cleanly in a single line with pacman::p_load().
For basic usage, this article((pacman de pakkēji no insutōru rōdo o kantan ni suru. Published December 15, 2018. Accessed February 21, 2021. https://blog.atusy.net/2018/12/15/pacman/)) and this article(("install.packages()" suru no wa kore ga saigo! R no pakkēji kanri ni wa "pacman" o tsukaō. Qiita. Accessed February 21, 2021. https://qiita.com/taiyodayo/items/e69d997754d55e3d7e4c)) are helpful references.
When you share a script with someone else, they might not have {pacman} installed. Taking that into account, I write the code as follows.
if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, magrittr, package_n)Code language: PHP (php)
Clearing the environment and freeing memory
On another note, if previous results remain when you run a new script, you might miss errors or end up with miscalculations. For this reason, I clear the environment with rm(list=ls()) and run garbage collection (freeing unused memory space) with gc().
I referred to this article((2020-nenban R ni yoru dēta bunseki memo. Qiita. Accessed February 21, 2021. https://qiita.com/gnbrganchan/items/f001007098d873e0b0ca)) for the code.
rm(list=ls())
gc(); gc();Code language: PHP (php)
The reason for running garbage collection twice is explained below.
Summary of header code
- Using {pacman}
- Clearing the environment and freeing memory
Combining these, I include the following at the beginning of each script.
rm(list=ls()); gc(); gc();
if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, magrittr, package_n)Code language: PHP (php)
Because I also frequently use the compound assignment pipe operator %<>%, I load tidyverse and magrittr separately. I also recommend setting up RStudio on Docker so that it does not depend on your PC's environment. Please see this article as well.