SyntaxStudy
Sign Up
R Working with Packages and the R Environment
R Beginner 1 min read

Working with Packages and the R Environment

R's power comes largely from its ecosystem of packages. CRAN hosts over 20,000 packages covering everything from machine learning to bioinformatics. Installing a package requires only install.packages("name"), while loading it into the current session uses library(name) or require(name). Best practice is to call library() at the top of every script so dependencies are explicit. The R environment is organised as a hierarchy of nested environments. The global environment (.GlobalEnv) is where user-defined objects live during an interactive session. When a function is called, a new child environment is created for that call, and variable lookup walks up the parent chain until the object is found or the empty environment is reached. The functions ls(), rm(), and exists() help you inspect and manage the contents of the global environment. Session management functions like getwd(), setwd(), and the here package for project-relative paths are critical for reproducible work. Saving and loading workspaces with save.image() and load() allows you to persist your environment across sessions, though many practitioners prefer re-running clean scripts rather than relying on saved workspaces.
Example
# Installing packages (run once; comment out afterwards)
# install.packages("dplyr")
# install.packages(c("ggplot2", "tidyr", "readr"))

# Loading packages
library(stats)    # ships with base R; loaded by default
# library(dplyr)  # would load dplyr if installed

# Inspect the current environment
ls()                     # list all objects in .GlobalEnv
x <- 10
y <- "test"
ls()                     # now shows "x" and "y"
exists("x")              # TRUE
exists("z")              # FALSE

# Remove objects
rm(y)
ls()                     # "y" is gone

# Working directory management
original_wd <- getwd()
cat("Working dir:", original_wd, "\n")
# setwd("C:/my_project")   # change working directory

# Inspect a package's contents
# ls("package:stats")    # list exported names

# Session information (useful for reproducibility)
R.version.string         # e.g. "R version 4.3.1 (2023-06-16)"
Sys.time()               # current date-time
.Machine$integer.max     # 2147483647  — max integer value

# Saving / loading (workspace)
# save.image("session.RData")   # save entire workspace
# load("session.RData")         # restore workspace
# saveRDS(x, "x.rds")           # save a single object
# x <- readRDS("x.rds")         # restore a single object