R
Beginner
1 min read
Working with Packages and the R Environment
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