BudiBadu Logo
Samplebadu

R by Example: Packages

R 4.x

Extending R functionality with this sample code demonstrating package installation from CRAN, library loading for namespace access, ggplot2 for grammar of graphics visualization, dplyr for data manipulation with pipe operator, and double colon notation.

Code

# Installing a package (run once)
# install.packages("ggplot2")
# install.packages("dplyr")

# Loading packages
library(ggplot2)
library(dplyr)

# Using functions from a package
df <- data.frame(x = 1:10, y = (1:10)^2)

# Using ggplot2 for plotting
ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  geom_line(color = "blue") +
  ggtitle("Plot with ggplot2")

# Using dplyr for data manipulation
df_filtered <- df %>%
  filter(x > 5) %>%
  mutate(z = y * 2)

# Accessing function without loading (:: operator)
utils::head(df)

Explanation

R's package ecosystem extends the language's capabilities through CRAN (Comprehensive R Archive Network), which hosts thousands of contributed packages. Packages are installed using install.packages("name"), which downloads and installs the package files to the local library directory. Installation is required only once per machine or R installation, though packages may need updating as new versions are released.

To use a package in the current R session, it must be loaded using library(package), which makes the package's functions available in the global namespace. The double colon operator :: provides an alternative for accessing specific functions without loading the entire package, using syntax package::function(). This is useful for avoiding namespace conflicts when multiple packages define functions with the same name.

The example demonstrates two cornerstone packages of the tidyverse ecosystem. The ggplot2 package implements the Grammar of Graphics for declarative visualization, using ggplot() initialization, aes() for aesthetic mappings, geometric objects like geom_point(), and layering with +. The dplyr package provides a grammar of data manipulation with verbs like filter(), select(), mutate(), summarise(), and arrange(), connected using the pipe operator %>% (or native pipe |> in R 4.1+) for readable left-to-right data transformation workflows.

Code Breakdown

6
library(ggplot2) loads package making functions available in namespace.
13
ggplot(df, aes(...)) initializes plot with data and aesthetic mappings.
19
%>% pipe operator passes left side as first argument to right side function.
24
utils::head() accesses function without loading package using double colon.