1. Home
  2. Explore
  3. Computer Science
  4. Introduction to R

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Introduction to R

Introduction to R for Data Science

R is a programming language and environment designed especially for statistical analysis, data visualization, and data science. It allows analysts to import data, organize it, explore patterns, calculate descriptive statistics, create visualizations, and build statistical models.

This lesson develops a foundation in R by explaining:

  • Why R is useful
  • How to install and use R and RStudio
  • How packages extend R
  • How to create basic graphics
  • How to summarize and select data
  • How R stores data
  • How to enter and import data
  • How to perform introductory modeling with clustering, principal components, and regression

Why R Matters in Data Science

R is widely used by data-mining and data-science professionals. Python is another major tool in the field, but R is particularly strong for statistical work and data visualization.

Several characteristics make R valuable:

  • R is free. Unlike some commercial statistical programs that may cost thousands of dollars per year, R can be downloaded and used without a purchase.
  • R is open source. Its source code and development are supported by a broad community rather than being controlled exclusively by one commercial company.
  • R is designed for vector operations. Instead of writing a loop that processes one value at a time, an analyst can often apply one operation to an entire vector, row, column, or table.
  • R has a large community. Users share examples, documentation, solutions, and new tools.
  • R has thousands of contributed packages. These packages add specialized capabilities for nearly every area of data analysis.

A useful way to understand R is to think of the base language as a powerful workshop and packages as specialized tools. The basic workshop can accomplish many tasks, but additional tools make specialized tasks much faster and easier.

R is especially useful because it combines statistical functionality, data visualization, open-source development, and a large ecosystem of packages.


Setting Up R

Installing R

R itself must be installed before it can be used. The official R project website provides downloads for different operating systems.

The general installation process is:

  1. Visit the official R project website.
  2. Choose the download link.
  3. Select a download mirror. A cloud-based mirror can automatically direct the user to a suitable location.
  4. Choose the operating system:
    • macOS
    • Windows
    • Linux
  5. Download the appropriate installer.
  6. Follow the standard installation instructions.

On macOS, the download is typically a package installer. On Windows, the base installer is normally used. Linux users generally select the installation method appropriate for their distribution.

Installing R provides the computational engine. However, many users also install RStudio, which provides a more organized interface for working with R.


The Native R Interface

When R is opened directly, the interface commonly contains two important areas:

  • The source window, also called the script window, where code is written
  • The console window, where commands are executed and output appears

A script is a saved collection of R commands. Keeping commands in a script is useful because the analysis can be reproduced later instead of being retyped manually.

Comments

A line beginning with a pound sign, or hashtag, is a comment.

# This line is a comment

Comments are ignored when R runs the code. They are used to explain what a section of code does or to leave reminders for later.

Running Code

A line of code can be executed by placing the cursor on that line and using the appropriate keyboard shortcut, commonly Command + Enter on macOS or Control + Enter on Windows.

The command is sent to the console, and the result appears there.


Course Files and R Scripts

A collection of scripts and data files can be downloaded as a compressed folder. After downloading, the folder must be unzipped.

R script files use the .R extension:

analysis.R

The .R extension identifies a file containing R source code. Data files may be stored in a separate folder and loaded when needed.

A useful workflow is:

  1. Store scripts and data in an organized folder.
  2. Open the script in R or RStudio.
  3. Run commands from the script.
  4. Examine the output in the console or viewer.
  5. Save the script so the analysis can be reproduced.

RStudio

What RStudio Provides

RStudio is a separate application that works on top of R. R must already be installed, because RStudio provides the interface but does not replace the R engine.

RStudio improves the experience of using R in several ways:

  • It provides a unified interface.
  • It uses consistent keyboard shortcuts across operating systems.
  • It organizes scripts, console output, variables, plots, and help in one window.
  • It makes it easier to navigate and manage an analysis.
  • It allows panes to be resized and rearranged.

The free Community version is sufficient for ordinary statistical programming and data analysis.


The Main RStudio Panes

RStudio commonly displays four areas:

  1. Source pane
    This is where scripts are written and edited.

  2. Console pane
    This is where commands run and text output appears.

  3. Environment pane
    This displays objects currently stored in memory, such as data frames, vectors, and models.

  4. Files, plots, packages, and help pane
    This area can display graphs, files, installed packages, and documentation.

The exact arrangement can be changed. Dividers can be dragged to enlarge or reduce panes.


Using RStudio with a Dataset

A simple workflow uses the built-in iris dataset.

library(datasets)

head(iris)
summary(iris)
plot(iris)

The iris dataset contains measurements for three species of iris flowers:

  • Sepal length
  • Sepal width
  • Petal length
  • Petal width
  • Species

The head() function shows the first six rows. The summary() function provides quick descriptive information. The plot() function creates a basic visualization.

RStudio displays plots inside the plots pane rather than necessarily opening a separate window. This keeps the analysis organized.


Clearing the Workspace Display

The console can be cleared to make later output easier to read. Clearing the console removes displayed text but does not necessarily delete objects from memory.

Plots can also be cleared separately. Packages can be detached when they are no longer needed.

A distinction is important:

  • Clearing the console removes visible output.
  • Clearing plots removes displayed graphics.
  • Detaching a package removes its functions from the active search path.
  • Removing an object deletes a particular data object from the current environment.

Packages: Extending R

What Is a Package?

A package is a bundle of R code, documentation, and sometimes example data. Packages add functions that are not included in the basic R installation.

Packages make it possible to perform specialized tasks such as:

  • Cleaning data
  • Manipulating data frames
  • Processing text
  • Working with dates
  • Importing files
  • Creating interactive graphics
  • Building interactive web applications
  • Writing formatted reports

Packages are similar to extensions or plugins for other software. R provides the main environment, and packages add specialized capabilities.


Base Packages and Contributed Packages

There are two broad categories of packages.

Base Packages

Base packages are installed with R. They are already available on the computer, but many are not loaded automatically.

For example, the datasets package is installed with R and contains familiar datasets such as iris, mtcars, and lynx.

A package can be loaded with:

library(datasets)

Contributed Packages

Contributed packages, also called third-party packages, must generally be:

  1. Downloaded
  2. Installed
  3. Loaded

Installation makes a package available on the computer. Loading makes its functions available in the current R session.

These are different operations:

install.packages("psych")  # Install once, if needed
library(psych)             # Load during a session

A package may be installed but not currently loaded.


Where Packages Come From

CRAN

The Comprehensive R Archive Network, or CRAN, is the official repository for R packages. It provides:

  • Packages
  • Documentation
  • Installation files
  • Task views organized by topic

A task view groups packages by subject area, such as Bayesian statistics, computational physics, or chemometrics. This helps users find tools for a particular field.

CRANtastic

CRANtastic provides listings of popular and recently updated packages. It is useful for discovering packages, although actual package downloads are generally redirected to CRAN.

GitHub

GitHub is another source of R packages. It is especially common for packages that are under active development or have not yet been submitted to CRAN. Installing from GitHub usually requires a different process and is most useful when the package documentation specifically recommends it.


Commonly Used Packages

Several packages are especially useful in data science:

PackageMain purpose
dplyrManipulating data frames
tidyrCleaning and restructuring data
stringrWorking with text
lubridateWorking with dates and times
httrAccessing web data
ggplot2Creating data visualizations
ggvisCreating interactive visualizations
shinyCreating interactive web applications
rioImporting and exporting data
rmarkdownCreating rich reports and interactive documents
pacmanManaging packages

The package names may initially seem cryptic, but each one solves a recurring category of problems.


Using pacman

The pacman package can simplify package management. Its functions can install and load packages in a single workflow.

For example:

install.packages("pacman")
library(pacman)

p_load(dplyr, tidyr, stringr, lubridate, ggplot2, rio)

If one of the requested packages is not installed, p_load() can install it and then load it.

A package can also be accessed through the package namespace without loading it:

pacman::p_load(ggplot2)

The double colon means that a function is being called from a particular package.

Contributed packages can be unloaded with a package-management function such as:

p_unload(all)

Base packages, such as datasets, are detached using the standard R command:

detach("package:datasets", unload = TRUE)

Basic Data Visualization

Visualization should generally come before numerical analysis. A graph provides an initial impression of the data and can reveal patterns that numerical summaries may hide.

A graph can reveal:

  • The shape of a distribution
  • Differences between groups
  • Associations between variables
  • Gaps
  • Outliers
  • Possible data-entry problems
  • Whether the assumptions of a later analysis appear reasonable

The basic plot() function is a useful starting point because it adapts to the type and number of variables supplied.


The plot() Function

The general form is:

plot(data$variable)

The dollar sign selects a variable from a data frame. For example:

plot(iris$Species)

This means: use the Species variable from the iris data frame.

The type of graph produced depends on the data.


Plotting a Categorical Variable

A categorical variable places observations into named groups.

plot(iris$Species)

This produces a simple bar chart showing the number of observations in each species.

The iris dataset contains:

  • 50 setosa observations
  • 50 versicolor observations
  • 50 virginica observations

The equal group sizes are important because unbalanced groups can affect later analyses.


Plotting One Quantitative Variable

A quantitative variable represents a measured numerical amount.

plot(iris$Petal.Length)

R recognizes that petal length is quantitative. With one quantitative variable, the default plot uses the row index on the horizontal axis and the variable values on the vertical axis.

This graph is not always the most informative because the row number is merely an observation identifier. The vertical arrangement still provides some indication of the values and their grouping, but a histogram is usually better for understanding a single quantitative variable.


Plotting a Categorical and Quantitative Variable

When one variable is categorical and the other is quantitative, R automatically selects a useful comparison display:

plot(iris$Species, iris$Petal.Length)

This produces a box plot.

A box plot summarizes the distribution of a quantitative variable within each category. It helps compare:

  • Typical values
  • Spread
  • Possible outliers
  • Differences between groups

For petal length, the three iris species show strong separation. This indicates that petal length is useful for distinguishing the species.


Plotting Two Quantitative Variables

When two quantitative variables are supplied, plot() creates a scatterplot:

plot(iris$Petal.Length, iris$Petal.Width)

A scatterplot places one observation at the intersection of its two values. The graph reveals the association between the variables.

In the iris data, petal length and petal width have a strong positive association: flowers with longer petals generally also have wider petals.


Plotting an Entire Data Frame

plot(iris)

When an entire data frame is supplied, R creates a matrix of plots for the variables. Quantitative variables are compared with scatterplots, while categorical information may appear in a simpler display.

This provides a quick overall view of relationships among several variables. It is especially useful when the dataset has a modest number of variables.


Improving a Plot

Basic plots can be customized with optional arguments.

plot(
  iris$Petal.Length,
  iris$Petal.Width,
  col = "#D62728",
  pch = 19,
  main = "Petal Length and Petal Width",
  xlab = "Petal Length",
  ylab = "Petal Width"
)

Important graphical arguments include:

  • col: color
  • pch: point character
  • main: title
  • xlab: horizontal-axis label
  • ylab: vertical-axis label
  • cex: size multiplier
  • lwd: line width

A hexadecimal color code such as "#D62728" specifies a color precisely. pch = 19 produces solid circles.

These options can transform an exploratory graph into a clearer presentation or publication graphic.


Plotting Mathematical Functions

The plot() function can also display mathematical functions.

For example:

plot(cos, 0, 2 * pi)

This plots the cosine function from 000 to 2π2\pi2π.

An exponential function can also be plotted:

plot(exp, 1, 5)

A normal density curve can be plotted using dnorm():

plot(dnorm, -3, 3)

The normal density has the familiar bell-shaped form.

A customized normal curve could be created as follows:

plot(
  dnorm,
  -3,
  3,
  col = "red",
  lwd = 2,
  main = "Standard Normal Density",
  xlab = "Value",
  ylab = "Density"
)

The flexibility of plot() makes it useful both for exploring datasets and for visualizing mathematical functions.


Bar Charts

A bar chart is appropriate for categorical data. Each category receives a bar whose height represents its count or another summary value.

The raw observations usually need to be summarized first.

Why Raw Categorical Data Are Not Enough

Suppose the mtcars dataset contains a variable indicating the number of cylinders:

plot(mtcars$cyl)

Because each row contains one car, R may display a value for every individual case rather than one bar per cylinder category. The desired chart requires a frequency table first.

cylinders <- table(mtcars$cyl)
barplot(cylinders)

The table() function counts how many observations fall into each category. The result is then supplied to barplot().

The resulting graph shows that:

  • Four-cylinder cars are common.
  • Six-cylinder cars are less common.
  • Eight-cylinder cars are also strongly represented in this historical dataset.

This principle applies beyond R. Spreadsheet programs also generally require a summary table before creating a frequency bar chart.


Histograms

A histogram displays the distribution of a quantitative variable. It divides the numerical scale into intervals called bins and counts how many observations fall within each interval.

hist(iris$Sepal.Length)

The vertical axis usually shows frequency, meaning the number of observations in each interval.

A histogram helps the analyst examine:

  • Shape: symmetrical, skewed, or irregular
  • Modality: one peak, two peaks, or multiple peaks
  • Gaps: empty or nearly empty regions
  • Outliers: unusually high or low observations
  • Spread: how widely values vary

These features matter because unusual distributional patterns may affect the choice or interpretation of later statistical methods.


Examples from the Iris Data

hist(iris$Sepal.Length)
hist(iris$Sepal.Width)
hist(iris$Petal.Length)
hist(iris$Petal.Width)

Sepal width is approximately bell-shaped. Petal length and petal width show a large concentration at the low end, followed by a gap and another distribution at higher values.

This pattern suggests that species may be producing distinct groups within the overall distribution.


Histograms by Group

When groups differ, a single histogram can hide important information. Separate histograms can be placed together using graphical parameters.

par(mfrow = c(3, 1))

This means that the graphics device should display three rows and one column.

A grouped histogram can be created by selecting rows:

hist(
  iris$Petal.Length[iris$Species == "setosa"],
  xlim = c(0, 7),
  breaks = 8,
  main = "Petal Length: Setosa",
  xlab = ""
)

The same pattern can be used for versicolor and virginica.

The expression

iris$Species == "setosa"

creates a logical condition identifying rows belonging to the setosa group.

Using the same horizontal scale for all histograms is essential. Otherwise, differences between groups may appear larger or smaller simply because the graphs use different axes.

Small Multiples

A set of comparable graphs showing the same variable across groups is called small multiples.

Small multiples are useful because:

  • Each group receives its own distribution.
  • All groups can be compared directly.
  • Differences in shape, location, and spread become easier to see.

After changing graphical parameters, they should be restored:

par(mfrow = c(1, 1))

Scatterplots and Associations

A scatterplot is the standard graph for examining the relationship between two quantitative variables.

For example:

plot(mtcars$wt, mtcars$mpg)

Each point represents one car. Its horizontal position indicates weight, and its vertical position indicates miles per gallon.

The plot shows a strong downward pattern: heavier cars generally have lower fuel efficiency.


What to Examine in a Scatterplot

Linearity

The analyst should ask whether the relationship can reasonably be described by a straight line.

Many statistical procedures, including ordinary linear regression, assume that the association is approximately linear.

Consistent Spread

The spread of points should be examined across the horizontal axis.

If the points are tightly clustered in one region but widely spread in another, the pattern is called heteroscedasticity. Unequal spread can complicate statistical modeling.

Outliers

An outlier is an observation that is unusually far from the general pattern.

An especially influential case may have an unusual combination of predictor and outcome values. Such a point can substantially affect a correlation or regression line.

Direction and Strength

The analyst should determine whether the variables have:

  • A positive association
  • A negative association
  • Little or no association

The tighter the points follow a consistent pattern, the stronger the association generally appears.


Improving a Scatterplot

plot(
  mtcars$wt,
  mtcars$mpg,
  pch = 19,
  cex = 1.5,
  col = "#D62728",
  main = "Vehicle Weight and Fuel Economy",
  xlab = "Weight",
  ylab = "Miles per Gallon"
)

Solid, enlarged points and clear labels make the relationship easier to interpret.

A graph should usually be created before calculating a correlation or fitting a model. Visualization gives context to the numerical result.

A statistical analysis should begin with an understanding of what the data look like, not only with a numerical calculation.


Overlaying Plots

Overlaying plots means placing one graphical layer on top of another.

The purpose is to increase information density while preserving a coherent comparison. For example, a histogram can be overlaid with:

  • A theoretical normal curve
  • A kernel density estimate
  • A rug plot showing individual observations

The goal is not to add decoration. Each layer should contribute useful information.

Too many competing layers can overwhelm the reader. Effective graphics use restraint and combine views that support one another.


The Lynx Data Example

The built-in lynx dataset contains annual counts of Canadian lynx trapped over a long period.

hist(lynx)

The histogram is strongly skewed. Many observations are near the low end, while fewer observations extend toward high trapping counts.

A density histogram can be created with:

hist(
  lynx,
  probability = TRUE,
  col = "thistle",
  main = "Distribution of Lynx Trappings",
  xlab = "Number of Lynx Trapped"
)

Using probability = TRUE changes the vertical scale from counts to density, allowing curves to be placed meaningfully over the histogram.


Adding a Normal Curve

A normal curve with the same mean and standard deviation as the data can be added:

curve(
  dnorm(
    x,
    mean = mean(lynx),
    sd = sd(lynx)
  ),
  add = TRUE,
  col = "purple",
  lwd = 2
)

This curve answers a comparison question: how would the data look if they followed a normal distribution with the same center and spread?

The lynx data clearly do not match the normal curve because of their strong low-end concentration and skew.


Kernel Density Estimates

A kernel density estimate is a smooth, flexible representation of the observed distribution.

lines(
  density(lynx),
  col = "blue",
  lwd = 2
)

Unlike a normal curve, a kernel density estimate follows the shape of the actual data more closely.

The smoothness can be adjusted:

lines(
  density(lynx, adjust = 3),
  col = "purple",
  lwd = 2
)

A larger adjustment produces a smoother curve that changes more gradually. A smaller adjustment follows local features more closely.


Rug Plots

A rug plot places a small mark for each individual observation along the horizontal axis.

rug(lynx, col = "gray", lwd = 2)

The rug plot helps explain why the histogram has particular heights and why the density curve has its shape. It displays the raw observations beneath the summarized views.

An effective overlay can therefore combine:

  1. Histogram bars for grouped counts
  2. A theoretical normal curve
  3. A smooth empirical density curve
  4. Individual observation marks

Each layer reveals a different aspect of the same distribution.


Basic Numerical Summaries

After visual inspection, numerical summaries provide precision.

The type of summary depends on the type of variable:

  • Categorical variables require counts or frequencies.
  • Quantitative variables require measures of center, spread, and range.

The summary() Function

Categorical Variables

summary(iris$Species)

The output gives the frequency of each category:

  • setosa: 50
  • versicolor: 50
  • virginica: 50

Quantitative Variables

summary(iris$Sepal.Length)

For a quantitative variable, R reports:

  • Minimum
  • First quartile
  • Median
  • Mean
  • Third quartile
  • Maximum

The median is the middle value when observations are ordered. The mean is the arithmetic average. The first and third quartiles divide the central portion of the data into sections.

Comparing the mean and median can provide an initial indication of skewness. If they differ noticeably, the distribution may not be symmetrical.

Entire Data Frame

summary(iris)

R summarizes each quantitative variable numerically and the categorical Species variable with frequencies.

This is a fast way to inspect an entire dataset.


The describe() Function

The describe() function from the psych package provides more detailed information for quantitative variables.

library(psych)

describe(iris$Sepal.Length)

The output can include:

  • nnn: sample size
  • Mean
  • Standard deviation
  • Median
  • Trimmed mean
  • Median absolute deviation
  • Minimum
  • Maximum
  • Range
  • Skewness
  • Kurtosis
  • Standard error

The standard deviation describes the typical distance of observations from the mean. The trimmed mean is calculated after removing a specified proportion of extreme values, making it less sensitive to outliers. The median absolute deviation is another robust measure of spread.

Skewness describes asymmetry. Kurtosis describes aspects of the shape and tail behavior of a distribution. The standard error describes the estimated variability of a sample statistic.

To describe several variables at once:

describe(iris)

The output includes numerical summaries for quantitative variables. If a categorical variable is included, such as Species, its numerical output should be ignored because describe() is intended primarily for quantitative data.


Selecting Cases

Often, an analysis should focus on only part of a dataset. In R, cases can be selected by category, by numerical value, or by several conditions at once.

Rows are selected inside square brackets.


Selecting by Category

hist(
  iris$Petal.Length[iris$Species == "versicolor"],
  main = "Petal Length: Versicolor"
)

The condition selects only rows where the species is versicolor.

Text values must be:

  • Enclosed in quotation marks
  • Spelled exactly as they appear in the dataset
  • Capitalized correctly

The same method can select setosa or virginica.


Selecting by Numerical Value

hist(
  iris$Petal.Length[iris$Petal.Length < 2],
  main = "Petal Length Less Than 2"
)

This selects observations whose petal length is less than 222.

Other comparison operators include:

  • <: less than
  • >: greater than
  • <=: less than or equal to
  • >=: greater than or equal to
  • ==: equal to
  • !=: not equal to

The double equals sign is used for comparison. A single equals sign is not the usual comparison operator in R.


Selecting with Multiple Conditions

The ampersand means “and”:

iris$Petal.Length[
  iris$Species == "virginica" &
  iris$Petal.Length < 5.5
]

This selects cases that satisfy both conditions:

  1. The species is virginica.
  2. Petal length is less than 5.55.55.5.

Multiple conditions allow the analyst to drill down into a narrowly defined subgroup.


Saving a Subsample

If the same selection will be used repeatedly, it is more efficient to save it as a new data frame.

i.setosa <- iris[iris$Species == "setosa", ]

The comma separates row selection from column selection:

  • Before the comma: selected rows
  • After the comma: selected columns

Leaving the column area blank means that all columns should be retained.

The new object can then be analyzed repeatedly:

head(i.setosa)
summary(i.setosa$Petal.Length)
hist(i.setosa$Petal.Length)

Saving a subsample makes later code clearer and reduces repetition.


Data Types and Data Structures

R distinguishes between the type of data and the structure used to organize the data.

A data type describes what a value is. A data structure describes how values are arranged.


Basic Data Types

Numeric

Numeric values can be whole numbers or decimal values. R commonly stores numbers using double precision.

n1 <- 15
n2 <- 1.5

Both are normally stored as numeric values of type double.

Character

Character values contain text.

c1 <- "c"
c2 <- "This is text"

R uses character values for both individual letters and longer strings.

Logical

Logical values are Boolean values:

l1 <- TRUE
l2 <- FALSE

They can also be abbreviated as T and F, although writing TRUE and FALSE is clearer and safer.

Logical values are central to filtering and conditional operations.

Complex

Complex numbers contain real and imaginary components.

Raw

The raw type stores raw bytes and is used for lower-level data handling.


Common Data Structures

Vectors

A vector is a one-dimensional collection of values.

v1 <- c(1, 2, 3, 4, 5)

All elements of a vector must have the same basic type.

Examples include:

numeric_vector <- c(1, 2, 3)
character_vector <- c("red", "green", "blue")
logical_vector <- c(TRUE, FALSE, TRUE)

Even a single value is treated as a vector of length one in R.

The c() function means combine or concatenate.


Matrices

A matrix is a two-dimensional arrangement with rows and columns. All values must have the same type.

m1 <- matrix(
  c(TRUE, TRUE, FALSE, FALSE),
  nrow = 2
)

A matrix can also be filled by rows:

m2 <- matrix(
  c("A", "B", "C", "D"),
  nrow = 2,
  byrow = TRUE
)

Matrices use row and column indices. Columns do not inherently have the same named-variable structure that data frames do.


Arrays

An array extends a matrix to three or more dimensions.

array1 <- array(
  1:24,
  dim = c(2, 3, 4)
)

The dimensions specify the number of rows, columns, and additional layers or tables.

Arrays are useful for multidimensional data but can become difficult to interpret as the number of dimensions increases.


Data Frames

A data frame is a two-dimensional table whose columns may have different types.

For example:

df <- data.frame(
  numbers = c(1, 2, 3),
  words = c("a", "b", "c"),
  truth = c(TRUE, FALSE, TRUE)
)

The columns have different types, but they must all have the same number of rows.

A data frame is the R structure most similar to a spreadsheet:

  • Rows represent observations.
  • Columns represent variables.
  • Each column can have its own type.

Most imported spreadsheets become data frames.


Lists

A list is R’s most flexible structure.

list1 <- list(
  numeric_values = c(1, 2, 3),
  text_values = c("a", "b", "c", "d"),
  logical_values = c(TRUE, FALSE, TRUE, FALSE, TRUE)
)

A list can contain objects of different types, different lengths, and different structures. A list can even contain another list.

This flexibility is powerful but can make lists more difficult to inspect and manipulate. For many ordinary data-analysis tasks, a data frame provides a more practical balance between flexibility and organization.


Coercion

Coercion means converting an object from one type or structure to another.

Coercion can happen automatically or deliberately.

Automatic Coercion

When different types are combined in a single vector, R generally converts them to a common, more general type.

c(1, "b", TRUE)

Because character data can represent the other values as text, R converts all elements to character values.

The general hierarchy is often described as moving toward a less restrictive type:

  • Logical
  • Numeric
  • Character

This can be useful, but accidental coercion can also create problems. A column intended to be numeric may become character if even one nonnumeric text value is included.


Explicit Coercion

An object can be converted deliberately.

x <- 5
x_integer <- as.integer(x)

A character vector containing numeric text can be converted:

numbers_as_text <- c("1", "2", "3")
numbers <- as.numeric(numbers_as_text)

The quotation marks disappear because the values are now numeric.

A matrix can be converted to a data frame:

m <- matrix(1:9, nrow = 3)
df <- as.data.frame(m)

The visual arrangement may look similar, but the object now supports data-frame behavior and has column variables.


A Common Coercion Problem with cbind()

Combining columns with cbind() can unexpectedly convert all columns to one type.

combined <- cbind(
  c(1, 2, 3),
  c("a", "b", "c"),
  c(TRUE, FALSE, TRUE)
)

Because a matrix must have one common type, the values may all become character.

To preserve separate column types, use a data frame:

df <- data.frame(
  numbers = c(1, 2, 3),
  words = c("a", "b", "c"),
  truth = c(TRUE, FALSE, TRUE)
)

The choice between a matrix and data frame is therefore not merely about appearance. It determines how R stores and handles the variables.


Factors

A factor is a special attribute of a vector used to represent categorical data.

A factor stores:

  • A set of possible categories called levels
  • The category associated with each observation
  • The ordering of those levels, if specified

Internally, factors are often represented by integer codes, but they display meaningful labels.


Creating a Factor

x <- c(1, 2, 3)
x_factor <- as.factor(x)

The structure shows that the object is a factor with three levels.

Although the underlying codes are numeric, the values should be interpreted as categories rather than as measured quantities.


Assigning Labels

Suppose the numerical codes represent operating systems:

x <- c(1, 2, 3)

x_factor <- factor(
  x,
  labels = c("Mac OS", "Windows", "Linux")
)

The numerical code 111 is associated with Mac OS, 222 with Windows, and 333 with Linux.

The labels must be supplied in the correct order. Factors are useful when numbers are merely codes for categories.


Reordering Levels

The order of factor levels can be changed.

responses <- c(1, 2, 3)

ordered_responses <- factor(
  responses,
  levels = c(2, 1, 3),
  labels = c("Maybe", "Yes", "No"),
  ordered = TRUE
)

An ordered factor encodes a meaningful sequence. The displayed ordering can be used in tables and graphs.

The underlying values remain coded numerically, but the factor tells R how to interpret and order the categories.

Factors are particularly important in experimental research and categorical statistical analyses.


Entering Data Manually

Most substantial datasets are imported from files, but small datasets may be entered directly into R.

The assignment operator is:

<-

For example:

x <- 5

This can be read as “xxx gets 5.” The arrow emphasizes that the value on the right is assigned to the object on the left.

An equal sign may work in many situations, but the arrow is the conventional style for assignment in R.

In RStudio, the assignment operator can be inserted with a keyboard shortcut.


The Colon Operator

The colon operator creates consecutive values:

x1 <- 0:10

This produces the integers from 000 through 101010.

Reversing the endpoints creates a descending sequence:

x2 <- 10:0

The seq() Function

The seq() function creates more flexible sequences.

seq(1, 10)

A sequence can use a specified step size:

seq(30, 0, by = -3)

This generates values beginning at 303030, decreasing by 333, until reaching or passing the endpoint.


The c() Function

The c() function combines values in any specified order:

x3 <- c(5, 2, 9, 1, 7)

Unlike the colon operator, c() does not require the values to be sequential.


The scan() Function

The scan() function allows values to be entered interactively.

x4 <- scan()

R waits for values to be typed into the console. Each value is entered by pressing Enter. Pressing Enter twice ends the input.

This method can be convenient for quickly entering a small set of numerical values.


The rep() Function

The rep() function repeats values.

rep(TRUE, 5)

This produces five TRUE values.

A group of values can be repeated as a pattern:

rep(c(TRUE, FALSE), 5)

This repeats the pair five times:

TRUE FALSE TRUE FALSE TRUE FALSE ...

To repeat each value several times before moving to the next:

rep(c(TRUE, FALSE), each = 5)

This produces five TRUE values followed by five FALSE values.


Importing Data

Importing is usually the most common way to bring data into R. It is more efficient than entering a large dataset manually.

Common formats include:

  • CSV: comma-separated values
  • TXT: plain text files
  • XLS: older Excel workbooks
  • XLSX: newer Excel workbooks
  • JSON: JavaScript Object Notation, common in web-based data

The rio Package

The rio package provides a consistent way to import and export many formats.

library(rio)

data_csv <- import("data.csv")
data_txt <- import("data.txt")
data_excel <- import("data.xlsx")

The main advantage is that the same import() function can often identify the file format automatically.

The imported object will commonly be a data frame.


Viewing Imported Data

The View() function opens a spreadsheet-like display:

View(data_csv)

In RStudio, the data viewer allows columns to be inspected and often sorted.

The imported data should still be checked carefully. Important checks include:

  • Are the column names correct?
  • Were missing values recognized?
  • Are numerical columns actually numeric?
  • Were dates imported correctly?
  • Were categorical variables interpreted appropriately?
  • Are there unexpected extra rows or columns?

Built-In Import Functions

R also includes more specific import functions.

For tab-delimited text:

read.table(
  "data.txt",
  header = TRUE,
  sep = "\t"
)

Here:

  • header = TRUE indicates that the first row contains variable names.
  • sep = "\t" specifies that tabs separate the columns.

For comma-separated files:

read.csv(
  "data.csv",
  header = TRUE
)

Because the function is specifically for CSV files, the comma separator is already understood.

The built-in functions are useful to recognize because existing R code often uses them, even when a package such as rio provides a simpler interface.


Excel Import Considerations

Excel files can be imported, but plain-text formats such as CSV or tab-delimited files are often more dependable and portable.

A practical workflow is:

  1. Open the spreadsheet.
  2. Export the needed sheet as CSV or tab-delimited text.
  3. Import the resulting file into R.

This avoids complications related to:

  • Multiple sheets
  • Formatting
  • Hidden cells
  • Merged cells
  • Excel-specific features
  • Locale differences in decimal and thousands separators

Introductory Modeling

Modeling uses data to describe structure, group observations, reduce complexity, or predict outcomes.

The following methods provide an introduction to three important types of modeling:

  • Hierarchical clustering
  • Principal component analysis
  • Regression

These methods answer different questions.

MethodMain question
Hierarchical clusteringWhich observations are similar to one another?
Principal component analysisCan many variables be represented with fewer dimensions?
RegressionHow can several predictors be used to predict an outcome?

Hierarchical Clustering

The Main Idea

Hierarchical clustering groups observations according to similarity.

The basic question is:

Which cases are most like one another based on the variables supplied?

For example, cars can be grouped according to fuel economy, weight, horsepower, cylinders, and other measurements.

The result is not an objective property of the observations alone. It depends on:

  • Which variables are included
  • How similarity or distance is measured
  • Which clustering method is used
  • Which observations are analyzed

Distance and Similarity

One common measure is Euclidean distance. In a two-dimensional example, the distance between two points can be represented by the straight-line distance between them.

More generally, for points with multiple coordinates, Euclidean distance is based on the square root of the sum of squared coordinate differences:

d(x,y)=∑j=1p(xj−yj)2d(\mathbf{x},\mathbf{y}) = \sqrt{\sum_{j=1}^{p}(x_j-y_j)^2}d(x,y)=j=1∑p​(xj​−yj​)2​

The closer two observations are in this multidimensional space, the more similar they are according to the selected variables.


Divisive and Agglomerative Methods

Hierarchical clustering can proceed in two directions:

  • Agglomerative clustering: Begin with every observation in its own group and combine groups.
  • Divisive clustering: Begin with all observations together and split them into smaller groups.

The example uses a divisive interpretation: observations begin together and are gradually separated.

The number of groups does not have to be specified in advance. The hierarchy displays possible groupings at different levels.


Preparing the Data

The mtcars dataset contains measurements for 32 cars. A subset of useful variables can be selected:

cars <- mtcars[, c(1:4, 8, 9:11)]

The blank before the comma means all rows are retained. The expression after the comma selects particular columns.

Removing irrelevant or redundant variables matters because the selected variables determine the distance calculations and therefore the resulting clusters.


Performing the Analysis

distances <- dist(cars)
hc <- hclust(distances)

plot(hc)

The dist() function calculates distances between observations. The hclust() function performs hierarchical clustering.

The resulting graph is called a dendrogram. Its branches show how observations are grouped and separated.

Cars that join near the bottom of the dendrogram are more similar according to the supplied variables. Cars that remain separate until higher levels are less similar.

Examples of sensible groupings may include:

  • Honda Civic and Toyota Corolla
  • Small Italian sports cars
  • Large American luxury cars

An unusual car may appear as a branch separated from most others.


Drawing Cluster Boundaries

Cluster boundaries can be added to make groupings easier to see:

rect.hclust(hc, k = 3, border = "blue")

The value of kkk indicates how many groups are highlighted. Several possible values of kkk can be examined because the dendrogram represents a hierarchy rather than one uniquely correct grouping.

Clustering can be applied in market analysis, audience segmentation, biological classification, and many other contexts.

A cluster is meaningful only relative to the observations, variables, distance measure, and algorithm used to create it.


Principal Component Analysis

The Main Idea

Principal component analysis, or PCA, is a dimensionality-reduction method.

Dimensionality reduction seeks to represent many variables with fewer composite dimensions while preserving as much important variation as possible.

The motivation is that fewer variables can mean:

  • Less noise
  • Simpler interpretation
  • Easier visualization
  • More manageable modeling
  • Reduced redundancy

A Geometric Interpretation

Suppose observations are measured on two variables, xxx and yyy, and show a strong linear pattern.

PCA finds a direction through the cloud of points that captures as much variation as possible. The first principal component runs along the dominant direction of the data.

Each observation can then be represented by its position along that direction. The two-dimensional data are summarized using one main dimension, with some information lost but much of the overall pattern retained.

The remaining perpendicular direction represents variation not captured by the first component.

The same idea extends to more than two variables. PCA finds a sequence of new axes:

  • Principal component 1 captures the greatest possible variance.
  • Principal component 2 captures the greatest remaining variance while being perpendicular to component 1.
  • Later components capture progressively smaller amounts of remaining variance.

Centering and Scaling

Before PCA, variables may need to be placed on comparable scales.

Centering subtracts the mean from each variable so that its mean becomes zero.

Scaling adjusts the variables so that their variances or standard deviations are comparable.

Without scaling, a variable measured in large numerical units might dominate the analysis simply because of its scale.

A PCA can be performed with:

pc <- prcomp(
  cars,
  center = TRUE,
  scale. = TRUE
)

Centering and scaling ensure that the analysis emphasizes patterns of variation rather than arbitrary measurement units.


Interpreting Components

If the original data contain ppp variables, PCA can produce up to ppp components.

However, the important question is how much variation each component explains.

summary(pc)

The standard deviations of the components indicate their relative importance. A large standard deviation means that the component captures substantial variation.

A scree plot helps visualize the decline:

screeplot(pc)

A sharp drop followed by smaller changes suggests that the first few components may summarize most of the meaningful structure.

The exact number of components to retain depends on the purpose of the analysis and the evidence from the component variances.


Loadings

The rotation or loading matrix describes the relationship between the original variables and the components.

pc$rotation

Large positive or negative loadings indicate that an original variable contributes strongly to a component.

For example, if weight, displacement, cylinders, and horsepower have similar loadings on the first component, that component may represent a general “large and powerful vehicle” dimension.


Scores

The position of each observation on each principal component is called its score.

predict(pc)

The scores show where individual cars lie along the newly created dimensions.

A biplot combines information about observations and variables:

biplot(pc)

In a biplot:

  • Points or labels represent observations.
  • Arrows represent original variables.
  • The first principal component is usually shown horizontally.
  • The second principal component is usually shown vertically.

Variables pointing in similar directions tend to be positively associated. Variables pointing in opposite directions tend to be negatively associated. Longer arrows generally indicate stronger contributions to the displayed dimensions.

PCA may reveal broad dimensions such as:

  • Large versus small
  • Slow versus fast
  • Powerful versus economical

Where clustering groups observations, PCA helps reveal the dimensions along which variables and observations differ.


Regression

The Main Idea

Regression predicts one outcome using one or more predictor variables.

The general linear regression form is:

Y=β0+β1X1+β2X2+⋯+βpXp+εY = \beta_0 + \beta_1X_1 + \beta_2X_2 + \cdots + \beta_pX_p + \varepsilonY=β0​+β1​X1​+β2​X2​+⋯+βp​Xp​+ε

where:

  • YYY is the outcome
  • β0\beta_0β0​ is the intercept
  • β1,β2,…,βp\beta_1,\beta_2,\ldots,\beta_pβ1​,β2​,…,βp​ are regression coefficients
  • X1,X2,…,XpX_1,X_2,\ldots,X_pX1​,X2​,…,Xp​ are predictors
  • ε\varepsilonε is unexplained error

Regression is sometimes summarized as “many variables predicting one variable.”


Preparing Predictors and Outcome

The USJudgeRatings dataset contains lawyers’ ratings of judges. Several rating variables can be used as predictors, while retention is the outcome.

A predictor matrix can be constructed by excluding the outcome column:

data <- USJudgeRatings

x <- as.matrix(data[, -12])
y <- data[, 12]

Here:

  • x contains the predictors.
  • y contains the outcome.

Fitting a Linear Model

The simplest regression model includes all predictors simultaneously:

reg <- lm(y ~ x)

The tilde means “is predicted by.”

A more explicit formula can list each predictor individually:

reg <- lm(
  RTN ~ CONT + INTG + DMNR + DILG + CFMG +
    DECI + PREP + FAMI + ORAL + WRIT + PHYS,
  data = USJudgeRatings
)

Both forms represent the same general modeling idea.


Regression Coefficients

reg

The coefficients include:

  • The intercept, which is the predicted outcome when all predictors equal zero
  • A coefficient for each predictor

A coefficient describes the expected change in the outcome associated with a one-unit increase in that predictor, holding the other predictors constant.

For example, a positive coefficient indicates that higher values of a predictor are associated with higher predicted outcome values after accounting for the other predictors.


Statistical Summary

summary(reg)

The summary provides:

  • Coefficients
  • Standard errors
  • ttt statistics
  • ppp values
  • Residual information
  • Multiple R2R^2R2
  • Adjusted R2R^2R2
  • Overall model tests

The coefficient test evaluates whether a predictor contributes evidence of an association with the outcome after the other predictors are considered.

A small ppp value, often below 0.050.050.05, is commonly treated as evidence that the coefficient differs from zero under the model assumptions.

The multiple R2R^2R2 describes the proportion of variation in the outcome explained collectively by the predictors:

R2=1−unexplained variationtotal variationR^2 = 1 - \frac{\text{unexplained variation}} {\text{total variation}}R2=1−total variationunexplained variation​

A high R2R^2R2 indicates strong predictive performance within the analyzed dataset, although it does not by itself guarantee strong performance on new data.


Additional Regression Information

An analysis-of-variance table can be obtained with:

anova(reg)

Confidence intervals for coefficients can be calculated with:

confint(reg)

A 95%95\%95% confidence interval gives a range of plausible values for each coefficient under the model.

Residuals are the differences between observed and predicted outcomes:

ei=yi−y^ie_i = y_i - \hat{y}_iei​=yi​−y^​i​

They can be examined directly:

residuals(reg)

A histogram provides a more interpretable overview:

hist(residuals(reg))

Residual analysis helps determine whether predictions are generally close and whether unusual cases or nonnormal patterns may be present.


Other Regression Approaches

Several alternative regression methods can be used when ordinary simultaneous regression is not ideal.

Stepwise Regression

Stepwise methods add or remove predictors according to selected criteria. They can be convenient but may produce unstable models and are often criticized for problems related to variable selection and generalizability.

Stagewise Regression

Stagewise regression adds predictors gradually in a way related to stepwise methods but can have different behavior and may generalize differently.

Least Angle Regression

Least angle regression, or LAR, is designed for situations involving many predictors and can build a sequence of models efficiently.

Lasso Regression

The least absolute shrinkage and selection operator, or lasso, adds a penalty that encourages some coefficients to shrink toward zero.

A simplified lasso objective can be represented as:

minimize[∑i=1n(yi−y^i)2+λ∑j=1p∣βj∣]\text{minimize} \left[ \sum_{i=1}^{n}(y_i-\hat{y}_i)^2 + \lambda\sum_{j=1}^{p}|\beta_j| \right]minimize[i=1∑n​(yi​−y^​i​)2+λj=1∑p​∣βj​∣]

The penalty controlled by λ\lambdaλ can reduce overfitting and may effectively remove some predictors by shrinking their coefficients to zero.

Different regression approaches can have similar predictive performance in one dataset but differ substantially in another. The appropriate method depends on the research goal, the number of predictors, the sample size, and the need for interpretability or prediction.


A Practical R Analysis Workflow

The concepts in this lesson fit together into a general workflow.

Step 1: Obtain and Organize the Data

The data may be:

  • Entered manually
  • Imported from a CSV file
  • Imported from a text file
  • Imported from an Excel workbook
  • Retrieved from a web or JSON source

Step 2: Inspect the Data

Use commands such as:

head(data)
summary(data)
str(data)

These reveal the first observations, basic summaries, and internal structure.

Step 3: Identify Data Types

Determine whether variables are:

  • Quantitative
  • Character
  • Logical
  • Categorical factors
  • Dates or other specialized formats

Step 4: Visualize the Data

Use:

  • Bar charts for categorical variables
  • Histograms for quantitative variables
  • Box plots for quantitative variables across categories
  • Scatterplots for associations between quantitative variables
  • Overlaid plots when complementary layers clarify the distribution

Step 5: Calculate Numerical Summaries

Use:

summary(data)

For more detail:

psych::describe(data)

Step 6: Select Relevant Cases and Variables

Use row and column indexing to focus the analysis:

subset_data <- data[data$group == "A", ]

Step 7: Transform Data When Necessary

Use coercion, factors, scaling, or restructuring to place the data in an appropriate form.

Step 8: Fit an Appropriate Model

Possible goals include:

  • Grouping similar observations with clustering
  • Reducing dimensionality with PCA
  • Predicting an outcome with regression

Step 9: Examine Assumptions and Results

Graphs, residuals, confidence intervals, and model summaries help determine whether the conclusions are reasonable.


Comprehensive Review

R is a free, open-source environment especially suited to statistical analysis and data visualization. Its vector-oriented design reduces the need for explicit loops, while its large package ecosystem extends the language into specialized fields.

RStudio provides a unified workspace containing scripts, the console, the environment, plots, and help. Packages add new functions; installation places them on the computer, while loading makes them available in the current session. CRAN is the primary official package repository, and tools such as pacman can simplify package management.

R works with several data types, including numeric, character, logical, complex, and raw values. These values can be organized into vectors, matrices, arrays, data frames, and lists. Data frames are especially important because they allow different column types while preserving a spreadsheet-like structure. Coercion converts objects between types or structures, either automatically or explicitly. Factors represent categorical variables using levels and optional labels or ordering.

Data can be entered using the assignment operator, the colon operator, seq(), c(), scan(), and rep(). Larger datasets are usually imported from CSV, text, Excel, or JSON files. The rio package provides a consistent import interface, while built-in functions such as read.table() and read.csv() offer more specific alternatives.

The plot() function adapts to its input: it can produce bar charts, box plots, scatterplots, plot matrices, and mathematical curves. Histograms reveal distributional shape, gaps, modality, spread, and outliers. Scatterplots reveal linearity, direction, strength, unequal spread, and unusual observations. Overlaying complementary graphical layers can provide richer information without requiring separate graphs.

Numerical summaries add precision after visual inspection. summary() gives frequencies for categorical variables and minimum, quartiles, median, mean, and maximum for quantitative variables. describe() provides additional statistics such as standard deviation, skewness, kurtosis, and standard error.

Finally, R supports introductory modeling. Hierarchical clustering groups similar observations and displays their relationships with a dendrogram. Principal component analysis reduces many variables to fewer dimensions while preserving important variation. Regression predicts one outcome from one or more predictors and provides coefficients, significance tests, confidence intervals, residuals, and measures of explained variation. Together, these tools form a foundation for exploring data, discovering structure, and building evidence-based statistical analyses.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent