3.8 Packages and Comments

3.8.1 Using Comments

In R, anything after a # symbol on a line is a comment — it is ignored by the program. Comments are essential for documenting your code.

# This is a comment in R. It is ignored by the program.

Use comments to:

  • Explain the purpose of functions or code blocks
  • Provide instructions to other developers (or your future self)
  • Temporarily disable lines of code for testing
  • Leave notes for future improvements

3.8.2 Installing and Loading Packages

Packages are collections of R functions, data, and documentation created by the R community. They extend R’s capabilities for data manipulation, statistical analysis, visualization, and more. Packages are installed from the Comprehensive R Archive Network (CRAN) and loaded into your session as needed.

# Install a package (only needed once)
install.packages("package_name")

# Load a package (needed each session)
library("package_name")

Throughout this textbook, we use the pacman package to streamline package management. The p_load() function installs missing packages automatically and loads them in one step.

3.8.3 Managing the Workspace

The workspace is R’s current working environment, where all your variables, functions, and datasets are stored. Use ls() to list objects and rm() to remove them.

ls()              # List all objects in the workspace
rm(object_name)   # Remove a specific object