Introduction to R
R for Data Science: Comprehensive Study Notes
Why R Matters in Data Science
R is a programming language and software environment designed especially for statistics, data analysis, and data visualization. It is widely used by data-mining and data-science professionals and is considered one of the major languages for working with data, alongside Python.
R is particularly valuable for the following reasons:
Free and open source: R can be downloaded and used without licensing fees. Commercial statistical software may cost thousands of dollars per year.
Efficient vector operations: R is designed to operate on entire vectors, rows, columns, or tables at once. This often eliminates the need to write explicit
forloops.Large and supportive community: Users can find tutorials, examples, troubleshooting advice, and ongoing software developments.
Extensive package ecosystem: Thousands of contributed packages add specialized functions for statistics, data manipulation, visualization, web data, machine learning, reporting, and many other tasks.
Broad functionality: With its packages, R can perform nearly any common data-analysis task.
R is therefore useful not merely because of its base language, but because of the combination of its open-source foundation and the large collection of packages built by its community.
R’s central strength is its ability to combine statistical analysis, programming, visualization, and reproducible reporting in one environment.
Installing R and Working with Course Files
Installing R
R must be installed before another interface, such as RStudio, can be used.
The general installation process is:
Visit the official R Project website.
Choose the download link.
Select a nearby CRAN mirror, or use an automatic mirror-selection option.
Choose the operating system:
macOS: Download the package installer and follow the standard installation process.
Windows: Download the base installation and follow the standard setup instructions.
Linux: Use the installation method appropriate for the particular Linux distribution.
Downloading Script and Data Files
A collection of scripts and data files can be downloaded separately. These files are commonly stored in a compressed folder.
A file ending in
.Ris an R script file.R scripts contain comments and executable code.
Data files can be stored in a separate folder and loaded during analysis.
Opening an R script in R or RStudio allows the code to be edited and executed.
The Native R Interface
The standard R application generally contains:
Source or script window: The area where code is written and edited.
Console window: The area where commands are executed and output is displayed.
A line beginning with # is a comment. Comments are ignored when code runs and are used to explain an analysis or organize a script.
To execute a line of code, the user places the cursor on that line and presses the appropriate keyboard shortcut, commonly Command-Enter on macOS or Control-Enter on Windows.
Example: Loading and Exploring the Iris Data
The built-in datasets package contains the famous Iris data set, which records measurements for three species of iris flowers:
Sepal length
Sepal width
Petal length
Petal width
Species
The command head(iris) displays the first six rows. The summary() function gives quick descriptive information, including:
Minimum and maximum values
Quartiles
Mean
Category frequencies
A basic plot of the entire data frame produces a matrix of plots for the quantitative variables and a categorical display for the species variable.
RStudio
Purpose of RStudio
RStudio is an integrated development environment built to make working with R easier and more organized. It does not replace R; R must already be installed because RStudio functions as an interface on top of R.
RStudio improves the workflow in several ways:
Provides consistent keyboard shortcuts across operating systems.
Combines multiple windows into one organized interface.
Makes scripts, output, variables, plots, and documentation easier to manage.
Supports keyboard-based navigation.
Allows panes to be resized and rearranged.
Provides integrated help and data-viewing tools.
A free community version is sufficient for ordinary data-analysis work.
Main RStudio Panes
RStudio commonly includes four major areas:
Source Pane
The source pane is where R scripts are written, edited, and saved. It supports syntax highlighting, comments, code execution, and organized programming.
Console Pane
The console displays commands as they run and shows text output, warnings, and errors.
Environment Pane
The environment displays objects currently stored in memory, such as:
Variables
Data frames
Models
Vectors
Functions
Other R objects
Files, Plots, Packages, and Help Pane
This pane can display:
Graphs
Files
Installed packages
Help documentation
Data viewers
The panes can be resized by dragging the dividers between them.
Repeating the Iris Analysis in RStudio
The same analysis performed in the native R interface can be completed in RStudio:
Load the
datasetspackage.Use
head(iris)to inspect the first six rows.Use
summary(iris)to obtain descriptive statistics.Use
plot(iris)to produce a collection of graphical summaries.Clear plots, the console, or the environment when appropriate.
RStudio keeps the results in a more unified and navigable workspace.
R Packages
What Packages Are
An R package is a bundle of code, documentation, and sometimes data that adds functionality to R. Packages provide new functions and allow R to perform specialized tasks.
Packages are often described as giving R additional capabilities because they can extend the language to support almost any type of data work.
Base Packages and Contributed Packages
Base Packages
Base packages are installed automatically with R. They are available on the computer but are not always loaded into the active session by default.
Keeping some packages unloaded helps reduce memory use and prevents unnecessary functions from being added to the current workspace.
Contributed or Third-Party Packages
Contributed packages are created by other R users and organizations. They generally must be:
Downloaded and installed.
Loaded into the current R session.
Used through their functions.
Unloaded when no longer needed, if appropriate.
Installation makes a package available on the computer. Loading makes the package available for use in the current session.
Sources for Packages
CRAN
The Comprehensive R Archive Network, or CRAN, is the official repository for R packages. It provides:
Package downloads
Documentation
Installation information
Package descriptions
Task views
Task views organize packages by subject area, such as:
Bayesian inference
Chemometrics
Computational physics
Machine learning
Social science statistics
Time-series analysis
CRAN Task Listings
Sites that list popular or recently updated packages can help users discover packages. Actual package downloads are generally redirected to CRAN.
GitHub
GitHub hosts many R packages and development versions. Installing from GitHub may require a different process and is most useful when a package is not available through CRAN or when the newest development version is needed.
Commonly Used Packages
dplyr: Manipulates data frames and supports data transformation.
tidyr: Cleans and restructures data.
stringr: Works with character strings and text.
lubridate: Handles dates and times.
httr: Helps retrieve and work with web data.
ggvis: Supports interactive visualizations.
ggplot2: Creates sophisticated statistical graphics.
Shiny: Builds interactive web applications.
rio: Imports and exports data in multiple file formats.
R Markdown: Produces rich, reproducible documents and interactive notebooks.
pacman: Helps install, load, and unload packages efficiently.
Installing and Loading Packages
A package is commonly installed with an installation command, then loaded with either require() or library().
require()returns a confirmation message or status.library()loads the package without normally producing a confirmation message.
The pacman package simplifies package management. Its functions can:
Install packages if they are missing.
Load packages.
Load several packages in one operation.
Unload contributed packages.
A package can also be accessed through its namespace using the double-colon operator. This allows a function to be called directly from an installed package even if the package has not been fully attached to the search path.
Base packages require standard R commands for detaching or unloading them. Contributed packages can often be unloaded in groups through package-management tools.
Installing a package places it on the computer; loading a package makes its functions available in the current R session.
Basic Graphics in R
Why Graphics Come First
Before calculating statistics, it is useful to create visual summaries. Graphics provide a rapid impression of:
Distribution shape
Group differences
Relationships among variables
Outliers
Gaps
Potential data problems
A visual examination can help determine which statistical analyses are appropriate.
The Default plot() Function
The default plot() function is unusually flexible. It adapts its output according to:
The number of variables supplied.
Whether the variables are categorical or quantitative.
The structure of the object being plotted.
The resulting graph can be a bar chart, scatterplot, box plot, or scatterplot matrix.
Plotting a Categorical Variable
Plotting the species variable from the Iris data produces a bar chart showing the number of observations in each category:
Setosa: 50 observations
Versicolor: 50 observations
Virginica: 50 observations
This reveals that the data set contains three equally sized groups.
Plotting One Quantitative Variable
Plotting petal length alone produces a display in which:
The horizontal axis represents row or case order.
The vertical axis represents petal length.
The distribution and group pattern can still be observed.
The row number is generally not substantively meaningful, so this display is less informative than a histogram or grouped plot.
Plotting a Categorical and Quantitative Variable
When a categorical variable and a quantitative variable are supplied together, R commonly produces a box plot.
For example, plotting species and petal length produces separate distributions for the three species. This makes group differences clear and can show:
Group medians
Spread
Possible outliers
Separation or overlap among groups
Plotting Two Quantitative Variables
Plotting petal length against petal width produces a scatterplot. The Iris data show a strong positive association: flowers with longer petals generally also have wider petals.
Plotting an Entire Data Frame
Plotting the entire Iris data frame produces a scatterplot matrix for the quantitative variables. It allows a rapid, holistic examination of:
Pairwise associations
Possible clusters
Group differences
Overall variable patterns
This approach is especially useful when the number of variables is manageable.
Customizing Plots
Basic plots can be improved by specifying optional arguments, including:
Color: Changes the color of points or lines.
Point character: Controls the shape of plotted points.
Point size: Enlarges or reduces points.
Line width: Makes lines thicker or thinner.
Main title: Adds a title.
X-axis label: Describes the horizontal axis.
Y-axis label: Describes the vertical axis.
A plot with a meaningful title, labeled axes, consistent colors, and readable symbols is more suitable for presentations or publications than the default output.
Plotting Mathematical Functions
The plot() function can also graph mathematical functions and probability distributions.
Examples include:
A cosine function over an interval from 0 to 2π.
An exponential function over a selected range.
The density of a normal distribution over an interval such as −3 to 3.
A normal density curve has the familiar bell-shaped form. It can be customized using color, line width, title, and axis labels.
Bar Charts
Purpose of Bar Charts
A bar chart is the simplest standard graph for categorical data. It displays the frequency or count associated with each category.
Bar charts are useful when the categories themselves are the primary variable of interest.
Creating a Frequency Table First
A raw categorical variable usually contains one category value for each case. A bar-chart function may therefore plot each case individually rather than summarize the categories.
For example, plotting the cylinder variable in the motor-car data directly may produce a sequence showing the cylinder count for each car. This is not the desired frequency bar chart.
The data must first be summarized into a frequency table. The table() function counts the number of cases in each category. The resulting table can then be supplied to the bar-chart function.
Interpretation of the Motor-Car Example
The motor-car data include cars with:
Four cylinders
Six cylinders
Eight cylinders
The frequency chart shows:
Many cars with four cylinders.
Fewer cars with six cylinders.
A substantial number of cars with eight cylinders.
A default plot of the frequency table may produce a line-like display, but a bar chart is generally easier to interpret for categorical frequencies.
A bar chart normally requires summarized category counts rather than the raw category value for every individual case.
Histograms
Purpose of Histograms
A histogram is the most basic graph for a quantitative variable. It groups numerical observations into intervals, called bins, and displays the number of observations in each interval.
Histograms are used to examine:
Shape of the distribution
Symmetry
Skewness
Number of modes
Gaps
Outliers
Concentration of observations
Possible group mixtures
Distribution Shape
Important shapes include:
Symmetrical: High and low values are distributed similarly around the center.
Skewed: The distribution has a longer tail on one side.
Unimodal: One major peak.
Bimodal: Two major peaks, possibly indicating two underlying groups.
Gaps and Outliers
A gap is a region with few or no observations. It may indicate:
Separate subgroups
A natural division in the data
A measurement or data-entry issue
An outlier is an unusually high or low observation. Outliers may strongly affect means, correlations, regressions, and other analyses.
Histograms of the Iris Variables
The Iris data illustrate several distribution patterns:
Sepal length: A moderately distributed quantitative variable.
Sepal width: Approximately bell-shaped.
Petal length: A strong low-end cluster followed by a gap and another distribution.
Petal width: A similar low-end cluster and gap.
The gaps in petal length and petal width suggest that the three species may have substantially different distributions.
Grouped Histograms and Small Multiples
Histograms can be created separately for each species. This requires:
Selecting the rows belonging to one species.
Plotting the same quantitative variable for that subgroup.
Repeating the process for the other species.
Arranging the plots in multiple rows or columns.
For meaningful comparison, all histograms should use:
The same horizontal-axis limits.
Comparable bin definitions.
Consistent measurement units.
The three Iris species show that:
Setosa has very small petal measurements.
Versicolor and virginica have larger measurements.
Versicolor and virginica overlap but remain distinguishable.
This arrangement is called small multiples: multiple versions of the same graph are shown on a common scale so that groups or conditions can be compared directly.
Graphical settings changed with a parameter should be restored afterward so later plots are not unintentionally arranged in the same layout.
Scatterplots
Purpose of Scatterplots
A scatterplot displays the relationship between two quantitative variables. Each point represents one case located according to its values on the horizontal and vertical axes.
Scatterplots help examine:
Direction of association
Strength of association
Linearity
Spread
Outliers
Clusters
Heteroscedasticity
Key Features to Examine
Linearity
A relationship is linear when it can be reasonably described by a straight line. Many statistical procedures, including ordinary linear regression and correlation-based methods, assume approximate linearity.
Consistent Spread
The variability of the vertical values should remain reasonably consistent across the horizontal axis.
When the spread changes substantially—often forming a funnel or fan shape—the data exhibit heteroscedasticity. This can complicate regression and other statistical analyses.
Outliers
Outliers may be:
Unusual values on one variable.
Unusual combinations of values on both variables.
An unusual combination can have a particularly strong effect on a correlation or regression line.
Correlation
A scatterplot provides a visual impression of the direction and strength of the relationship. A positive association means that higher values of one variable tend to accompany higher values of the other. A negative association means that higher values of one variable tend to accompany lower values of the other.
Example: Weight and Fuel Efficiency
The motor-car data show a strong negative relationship between vehicle weight and miles per gallon:
Heavier cars generally have lower fuel efficiency.
Lighter cars generally have higher fuel efficiency.
The pattern is close to linear.
A few very heavy cars have particularly poor fuel efficiency.
A customized scatterplot can improve readability by using larger filled points, color, a title, and descriptive axis labels.
Data visualization should generally precede numerical analysis because graphs reveal patterns and problems that numerical summaries may hide.
Overlaying Plots
Purpose of Overlaying
Overlaying plots means placing multiple graphical summaries on the same coordinate system. The purpose is to increase information density and compare complementary views of the same data.
Useful overlays may include:
A histogram and a theoretical normal curve.
A histogram and one or more kernel density estimates.
Individual observations shown with a rug plot.
Multiple fitted or reference lines.
Benefits and Risks
Overlaying can:
Show multiple aspects of a distribution.
Compare observed data with a theoretical model.
Reveal patterns that one graph alone might miss.
Provide greater insight within the same space.
However, too much information can make a graph confusing. Effective graphics use restraint.
Overlay views that complement one another; do not combine visual elements merely because the software allows it.
Example: Canadian Lynx Trapping Data
The lynx data are a time series of Canadian lynx trapping counts over many years. A histogram of the values, ignoring the time order, shows:
Many observations at the low end.
A long upper tail.
A strongly skewed distribution.
A more customized histogram can use:
A selected number of bins.
Density rather than raw frequency.
A chosen fill color.
A descriptive title and axis label.
Normal Distribution Overlay
A normal-density curve can be overlaid using the same mean and standard deviation as the observed data. This allows comparison between:
The actual distribution.
A normal distribution with matching center and spread.
The comparison shows that the lynx values are not normally distributed because the data have a strong low-end concentration and a long upper tail.
Kernel Density Estimates
A kernel density estimate is a smooth, nonparametric estimate of a distribution.
Unlike a normal curve, a kernel estimate:
Does not assume a particular theoretical distribution.
Follows the observed data more closely.
Can contain multiple peaks and irregular shapes.
Represents a probability density whose total area is approximately one.
The smoothing parameter controls how closely the curve follows the data:
Less smoothing follows local peaks and gaps more closely.
More smoothing produces a slower-changing, smoother curve.
Rug Plot
A rug plot adds a small vertical mark for each individual observation along an axis. It shows the actual location of every data point and helps explain why:
Some histogram bins are taller.
A density curve rises or falls.
Certain areas contain clusters or gaps.
A combined histogram, normal curve, kernel estimates, and rug plot provides several complementary perspectives on one variable.
Basic Statistics
The summary() Function
After visual summaries, numerical summaries provide precision. The appropriate summary depends on the variable type.
Categorical variables: Counts or frequencies.
Quantitative variables: Minimum, quartiles, median, mean, and maximum.
Summary of a Categorical Variable
Applying summary() to the Iris species variable reports:
Setosa: 50
Versicolor: 50
Virginica: 50
These are category frequencies.
Summary of a Quantitative Variable
Applying summary() to sepal length provides:
Minimum
First quartile
Median
Mean
Third quartile
Maximum
The five-number summary consists of the minimum, first quartile, median, third quartile, and maximum. Comparing the mean with the median can provide a preliminary indication of skewness.
Summary of an Entire Data Frame
Applying summary() to the full Iris data frame summarizes each variable:
Quantitative columns receive numerical summaries.
The categorical species column receives category counts.
This is a fast way to obtain descriptive information for an entire data set.
More Detailed Descriptive Statistics with describe()
Purpose of describe()
The describe() function, available through the psych package, provides more detailed numerical summaries than the base summary() function.
For quantitative variables, it can report:
n: Sample size
Mean
Standard deviation
Median
Trimmed mean
Median absolute deviation
Minimum
Maximum
Range
Skewness
Kurtosis
Standard error
The function should generally be used for quantitative variables. It is not appropriate to interpret numerical output for categorical variables as though the categories were measurements.
Important Statistics
Standard Deviation
The standard deviation measures the typical distance of observations from the mean. A larger standard deviation indicates greater spread.
Trimmed Mean
A trimmed mean removes a specified proportion of extreme observations before calculating the mean. It can provide a measure of central tendency that is less affected by outliers.
Median Absolute Deviation
The median absolute deviation measures spread around the median and is relatively resistant to extreme scores.
Skewness
Skewness indicates asymmetry in a distribution. Positive skew generally means a longer upper tail, while negative skew generally means a longer lower tail.
Kurtosis
Kurtosis describes aspects of tail weight and peakedness relative to a reference distribution.
Standard Error
The standard error describes the sampling variability of a statistic, commonly the mean. It is not the same as the standard deviation of individual observations.
Using describe() on the Iris Data
describe(iris$Sepal.Length) provides detailed information for one quantitative variable.
Applying describe() to the entire Iris data frame produces a row for each variable. Numerical information for the species variable should be ignored because species is categorical, even if R internally represents it numerically.
Graphical summaries should still be examined before detailed numerical summaries. The two approaches complement one another:
Graphs reveal shape, gaps, clusters, and outliers.
Statistics provide exact numerical values.
Selecting Cases
Purpose of Case Selection
Case selection allows analysis to focus on a particular subgroup or range of observations. Cases can be selected by:
Category
Numerical value
Multiple conditions simultaneously
This supports more focused exploration and subgroup comparison.
Selecting by Category
Rows can be selected when a categorical variable equals a particular value.
For the Iris data, petal length can be plotted separately for:
Versicolor
Virginica
Setosa
The category must be written exactly as it appears in the data, including capitalization.
The selection condition uses two equal signs, which means “is equal to.” A single equal sign is generally used for assigning values, not testing equality.
Selecting by Quantitative Value
Rows can also be selected according to a numerical condition, such as:
Petal length less than 2.
Weight greater than a specified threshold.
A value within a selected interval.
A quantitative condition can sometimes select the same subgroup as a categorical condition, but the two methods differ conceptually:
Category selection uses a named group.
Numerical selection uses a measured criterion.
Combining Conditions
Multiple conditions can be joined with the ampersand operator, meaning “and.”
For example, a selection can require:
Species equals virginica.
Petal length is less than 5.5.
Only cases satisfying both conditions are included.
Other logical operators can be used to express alternatives or negations, but the key principle is that filtering conditions define the rows included in the analysis.
Saving a Subsample
If the same subgroup will be used repeatedly, it is efficient to save it as a new data frame.
The general structure is:
Select rows using a condition.
Leave the column position blank to retain all columns.
Assign the selected data to a new object.
The saved subsample can then be used for:
head()inspectionsummary()Histograms
Further statistical analyses
Saving a subgroup reduces repetition and makes later code easier to read.
Data Types and Data Structures
Data Types
A data type describes the kind of value stored in an object.
Numeric
Numeric values include:
Integers, which are whole numbers.
Double-precision values, which can represent decimal numbers.
R commonly stores numeric values as double precision by default.
Character
Character data contain text. R generally uses the character type for both individual characters and longer strings.
Logical
Logical data contain either:
TRUEFALSE
Logical values are not placed in quotation marks. Quotation marks would turn them into character values.
Complex
Complex values contain real and imaginary components.
Raw
Raw data represent low-level byte-oriented information.
Data Structures
A data structure describes how values are organized.
Vector
A vector is a one-dimensional collection of values.
Important features:
Values are arranged in a single sequence.
All elements must have the same basic type.
A vector containing one value is still a vector of length one.
Vectors are among R’s most fundamental data objects.
Examples include:
Numeric vectors
Character vectors
Logical vectors
The c() function combines values into a vector.
Matrix
A matrix is a two-dimensional arrangement with rows and columns.
Important features:
All values must have the same basic type.
Rows and columns are indexed numerically.
Matrix columns do not automatically have descriptive variable names.
Values may be entered in column order by default or arranged by row when requested.
Array
An array extends the matrix concept to three or more dimensions.
An array may be organized by:
Rows
Columns
Tables or additional dimensions
For example, an array can contain multiple two-dimensional tables.
Data Frame
A data frame is a two-dimensional structure resembling a spreadsheet.
Important features:
Columns may have different types.
All columns must have the same number of rows.
One column may be numeric, another character, and another logical.
Rows represent cases or observations.
Columns represent variables.
Data frames are the usual destination when spreadsheet data are imported.
Data frames are often the most useful balance between flexibility and ease of use.
List
A list is an ordered collection whose elements can have:
Different types
Different lengths
Different structures
A list can contain vectors, matrices, data frames, models, or other lists. Lists can be nested repeatedly.
Lists are highly flexible but can be more difficult to read and manipulate than data frames.
Data frames are often the most practical structure for ordinary data analysis, while lists provide the greatest flexibility.
Coercion
Meaning of Coercion
Coercion is the conversion of an object from one type or structure to another.
Examples include:
Character to logical
Character to numeric
Matrix to data frame
Double precision to integer
Matrix to another compatible structure
Coercion allows data to be placed into the form required by an analysis.
Automatic Coercion
When values of different types are combined, R may automatically convert them to a common type. The conversion generally moves toward the least restrictive or most general type.
For example, combining:
A numeric value
A character value
A logical value
may cause all values to become character values.
This can be problematic because the original numerical and logical properties are lost or hidden.
Explicit Coercion
Explicit conversion uses functions such as:
as.integer()as.numeric()as.data.frame()
A double-precision number can be converted to an integer. Character strings containing valid numerical values can be converted to numeric values, removing their quotation marks.
A matrix can be converted to a data frame. Although the contents may look identical, the resulting object supports data-frame functions and has named columns.
Combining Vectors into Data Frames
Combining vectors with a column-binding operation may unintentionally coerce all columns to the same type. If numeric, character, and logical vectors are combined directly, the result may become entirely character.
Explicitly constructing a data frame preserves the intended column types.
Factors
What Factors Are
A factor is an attribute of a vector used to represent categorical data. It records:
The possible category values, called levels.
The order of those levels.
The numerical coding used internally.
Factors are useful when categories need to be treated as categorical variables in statistical analyses.
Factor Levels
A factor may have levels such as:
123
Even if the underlying codes are integers, R treats the values as categories rather than ordinary numerical measurements.
The structure of a factor reports both:
The factor status.
The number and names of its levels.
Creating Factors
An existing vector can be converted into a factor. A numeric vector containing 1, 2, and 3 can therefore be treated as a categorical variable with three levels.
The object may still appear numerically encoded internally, but its statistical meaning is categorical.
Assigning Labels
Factor levels can receive descriptive labels. For example:
Code 1: macOS
Code 2: Windows
Code 3: Linux
The labels must be supplied in the same order as the underlying codes. R then displays the labels while retaining numerical codes internally.
This resembles the use of value labels in other statistical software.
Ordered Factors
Factor levels can be arranged in a meaningful order. For example, categories such as:
No
Maybe
Yes
can be ordered so that the levels represent increasing agreement or likelihood.
The order affects how R displays and sometimes analyzes the factor. Ordered factors are useful when categories possess a natural ranking, even if the distances between categories are not numerically equal.
Entering Data Manually
Assignment
The assignment operator stores a value in an object. It is conventionally written as a left-pointing arrow.
For example, the expression “x gets 5” stores the value 5 in the object named x.
An equal sign may also be understood in some contexts, but the left-arrow assignment operator is the conventional style for clear R programming.
RStudio provides a keyboard shortcut for inserting the assignment operator.
The Colon Operator
The colon operator creates a sequence of consecutive values.
A lower value followed by a higher value produces an ascending sequence.
A higher value followed by a lower value produces a descending sequence.
For example, a sequence from 0 through 10 contains every integer in that interval.
The seq() Function
The sequence function creates more flexible sequences. It can specify:
Starting value
Ending value
Step size
For example, a sequence can count downward from 30 to 0 in increments of 3.
The c() Function
The concatenate function combines arbitrary values into a vector. It is useful when values:
Are not consecutive.
Occur in an unusual order.
Need to be entered explicitly.
The scan() Function
The scan function allows values to be entered interactively in the console.
The general procedure is:
Run the scan function.
Enter a value.
Press Enter.
Continue entering values.
Press Enter twice to finish.
The resulting values are stored in a vector. This method can be useful when entering a small amount of data directly from a keyboard or numeric keypad.
The rep() Function
The repetition function creates repeated values.
A single logical value can be repeated a specified number of times. A vector of multiple values can also be repeated.
There are two important repetition patterns:
Repeat the complete sequence: A vector such as
TRUE, FALSEis repeated in alternating order.Repeat each element: Each value is repeated several times before moving to the next value.
These options allow structured data to be generated efficiently.
Importing Data
Common File Formats
Most real-world data are imported rather than typed manually.
CSV Files
CSV means comma-separated values. A CSV file is a plain-text representation of tabular data.
Advantages:
Can be exported by spreadsheet programs.
Can be read by most statistical software.
Is relatively portable.
Stores rows and columns without requiring a proprietary application.
Text Files
Text files may use tabs or other delimiters to separate values. They can be opened in text editors and word processors.
Excel Files
Excel data may be stored in older spreadsheet formats or newer .xlsx formats. Although R can read Excel files, importing them may create complications involving:
Multiple worksheets
Formatting
Missing values
Data types
Locale-specific decimal conventions
When possible, exporting an Excel worksheet to CSV or tab-delimited text is often more reliable.
JSON
JSON, or JavaScript Object Notation, is a structured text format commonly used for web data and application programming interfaces.
Importing with rio
The rio package simplifies data import and export by providing a unified import() function.
The same general command can import:
CSV files
Text files
Excel files
Other supported formats
The file extension helps rio determine how the file should be read. This avoids having to remember a separate import function for every format.
Imported Google Trends Data
The example data contain monthly relative search popularity for:
Mozart
Beethoven
Bach
The same information is supplied in CSV, text, and Excel formats. After importing, the data frame contains:
A month variable.
A relative popularity variable for each composer.
The head() function can confirm that the data were imported correctly.
Viewing Data
RStudio includes a data viewer that displays a data frame in a spreadsheet-like format.
The viewer allows users to:
Scroll through rows and columns.
Sort values by a column.
Inspect the imported data visually.
Confirm that variable names and values were read correctly.
Built-In Import Functions
R also includes lower-level import functions.
Reading Tab-Delimited Text
A general table-reading function can import a text file when the separator is specified as a tab. A header argument indicates that the first row contains variable names.
Missing values or blank cells may require explicit separator information.
Reading CSV Files
A CSV-specific function recognizes commas as delimiters, so the separator usually does not need to be specified manually.
The rio package uses functions of this general kind internally but provides a simpler interface.
Modeling Data
General Purpose of Modeling
Statistical modeling uses variables and relationships in the data to describe patterns, explain outcomes, classify cases, or generate predictions.
The introductory modeling examples include:
Hierarchical clustering
Principal component analysis
Regression
These methods address different questions.
Hierarchical Clustering
Purpose
Hierarchical clustering groups observations according to similarity. It is based on the principle of finding which cases are most like one another.
Possible applications include:
Market segmentation
Audience analysis
Grouping similar products
Identifying similar individuals or cases
Discovering structure in data
Important Decisions
Clustering depends on several choices:
Similarity or Distance Measure
The analyst must decide how similarity is measured. Euclidean distance is a common measure. It represents the geometric distance between cases in multidimensional space.
Number of Groups
Some clustering methods require the number of groups, often called k, to be selected in advance. Hierarchical clustering does not require the final number of groups to be fixed before the analysis.
Divisive and Agglomerative Approaches
Divisive clustering: Begins with all observations in one group and repeatedly splits them.
Agglomerative clustering: Begins with every observation in its own group and repeatedly combines groups.
The example uses a hierarchical, divisive approach with Euclidean distance.
Preparing the Data
The motor-car data contain numerous variables, but not all are necessarily useful for clustering. A subset of variables is selected, while all rows are retained.
The selected variables might include:
Miles per gallon
Number of cylinders
Engine displacement
Weight
Horsepower
Quarter-mile time
The choice of variables is crucial because clustering is based only on the information supplied.
Distance Matrix and Clustering
The analysis proceeds conceptually as follows:
Select the variables for analysis.
Calculate the distance between every pair of observations.
Apply the hierarchical clustering algorithm.
Plot the result.
A pipe allows the output of one step to become the input of the next step, making the sequence more concise.
Dendrogram
The result is displayed as a dendrogram, a tree-like diagram showing how observations split or combine.
Cases joining close together are more similar.
Cases separated at higher levels are less similar.
Horizontal cuts can be used to identify potential groups.
The example places several historically similar cars near one another, such as:
Honda Civic and Toyota Corolla
Small Italian sports cars
Large American luxury cars
An unusual car appears separated from most other observations because its selected characteristics differ substantially from the rest.
Interpreting Clusters Carefully
A cluster solution is valid only for:
The observations included.
The variables selected.
The distance measure used.
The clustering method applied.
Changing any of these can produce a different grouping. Clustering is therefore descriptive and data-dependent rather than an absolute discovery of permanent natural categories.
Boxes can be drawn around branches of the dendrogram to make possible two-, three-, four-, or five-group solutions easier to inspect.
Principal Component Analysis
Purpose
Principal component analysis, or PCA, is a method of dimensionality reduction. It transforms many correlated variables into a smaller number of new composite dimensions called principal components.
The purpose is to:
Reduce complexity.
Remove redundant information.
Reduce noise.
Make patterns easier to interpret.
Preserve as much important variation as possible.
PCA is based on the idea that fewer dimensions can sometimes retain most of the meaningful information in a data set.
Geometric Intuition
Suppose two variables form a diagonal cloud of points. PCA:
Finds the direction in which the data vary most.
Places a line through the data along that direction.
Measures the perpendicular distance from each point to the line.
Projects each point onto the line.
Represents the data with one primary dimension rather than two.
The first principal component is the direction that captures the greatest amount of variation.
Centering and Scaling
PCA often uses two preprocessing steps:
Centering
Centering subtracts the mean from each variable, making its mean equal to zero.
Scaling
Scaling adjusts variables so they have comparable variance, commonly unit variance. This prevents a variable with a large measurement scale from dominating the analysis merely because of its units.
Centering and scaling are especially important when variables are measured in very different units.
Components and Explained Variation
If the original data contain nine variables, PCA produces nine principal components. However, the components do not explain equal amounts of variation.
The first component explains the greatest amount.
The second explains the next greatest amount.
Later components explain progressively less.
Components with very little variation may contribute little useful information.
The standard deviation associated with a component indicates the amount of variation it captures. When the original variables are standardized, a component with a standard deviation greater than one explains substantial variation relative to an individual standardized variable.
Scree Plot
A scree plot displays the importance of successive components.
Analysts look for:
A sharp decline after the first few components.
An “elbow,” where additional components contribute relatively little.
Components that explain meaningful amounts of variance.
The number of components retained is partly a judgment about how much information is needed and how much complexity can be discarded.
Rotation or Loadings
The PCA rotation matrix, often interpreted as a loading matrix, describes the relationship between each original variable and each principal component.
Large positive or negative loadings indicate that a variable contributes strongly to a component. Loadings can be interpreted similarly to correlations between original variables and components.
Scores for Individual Cases
Each observation receives a score on every principal component. These scores show where each case falls in the reduced-dimensional space.
Cases with similar component scores have similar profiles on the original variables.
Biplot
A biplot displays:
Cases as labeled points.
Principal components as axes.
Original variables as directional arrows.
The direction and length of an arrow indicate how strongly a variable contributes to the component axes.
In the motor-car example, the first two components summarize broad dimensions such as:
Large, heavy cars versus small, efficient cars.
Slow cars versus fast cars.
An unusual car appears isolated, consistent with its separation in the clustering analysis.
Clustering Cases Versus Clustering Variables
The distinction between the two methods is important:
Hierarchical clustering: Groups cases according to similarity.
PCA: Reveals combinations or dimensions among variables.
PCA can therefore help identify broad latent dimensions that organize many original variables.
Regression
Purpose of Regression
Regression predicts one outcome variable from one or more predictor variables.
It can be summarized as:
Regression combines information from many variables to predict or explain variation in one outcome.
Regression is flexible and can be adapted to:
Explanation
Prediction
Variable selection
Model comparison
Classification-related tasks
Shrinkage and regularization
Predictor and Outcome Variables
The conventional notation is:
X: Predictor variables.
Y: Outcome or criterion variable.
A regression model estimates how the predictors jointly relate to the outcome.
Linear Model
A basic linear model can be represented as:
where:
β0 is the intercept.
β1,β2,…,βp are regression coefficients.
X1,X2,…,Xp are predictors.
ε is the residual or unexplained component.
Example: Ratings of Judges
The judge-rating data contain lawyers’ evaluations of judges on several dimensions, such as:
Diligence
Demeanor
Integrity
Other professional characteristics
Retention recommendation
The goal is to predict whether a judge should be retained using the other ratings.
The predictor variables can be assembled into a matrix X, while the retention variable serves as the outcome Y.
Simultaneous Entry Regression
In simultaneous entry regression, all predictors enter the model at the same time.
This provides an estimate of:
The unique coefficient for each predictor, controlling for the others.
The overall predictive ability of the set of variables.
The degree to which the predictors collectively explain the outcome.
Regression Coefficients
The model output includes:
Intercept: Predicted outcome when all predictors equal zero.
Slope coefficient: Expected change in the outcome associated with a one-unit increase in a predictor, holding other predictors constant.
A coefficient can be positive or negative depending on the direction of the predictor-outcome relationship.
Inferential Tests
A regression summary commonly reports:
Coefficient estimate
Standard error
Test statistic
Probability value
Significance indicators
The test statistic evaluates whether a coefficient differs from zero relative to its standard error. A small probability value suggests evidence that the predictor contributes to the model after controlling for the other variables.
Significance symbols are commonly used to mark conventional probability thresholds, such as p<.05.
Multiple R2
Multiple R2 indicates the proportion of outcome variability explained collectively by the predictors.
It can be expressed as:
An R2 close to 1 indicates strong predictive performance within the analyzed data, whereas an R2 close to 0 indicates that the predictors explain little of the outcome variation.
A high R2 does not automatically prove that the model will generalize well to new data.
ANOVA Table
The analysis-of-variance table separates model variation from residual variation.
It helps evaluate whether the model as a whole explains significantly more variation than would be expected from random error alone.
Confidence Intervals
Confidence intervals provide a range of plausible values for each regression coefficient. A 95% confidence interval describes an interval constructed by a method that would capture the true coefficient in approximately 95% of repeated samples under the model assumptions.
Residuals
A residual is the difference between an observed outcome and its predicted value:
where:
yi is the observed outcome.
y^i is the predicted outcome.
ei is the residual.
Residuals can be examined case by case or summarized graphically. A histogram of residuals helps assess whether they are:
Centered near zero.
Approximately symmetric.
Free of severe outliers.
Reasonably consistent with model assumptions.
Alternative Regression Methods
Several regression approaches can be used depending on the research goal.
Stepwise Regression
Stepwise regression adds or removes predictors according to statistical criteria. It can be convenient, but it has recognized limitations, including:
Instability across samples.
Inflated significance estimates.
Risk of overfitting.
Difficulty representing genuine theory.
Stagewise Regression
Stagewise regression resembles stepwise regression but is designed to have better generalizability in some settings.
Least Angle Regression
Least angle regression, or LARS, is a method for efficiently constructing regression models as predictors enter the model.
Lasso Regression
Lasso stands for least absolute shrinkage and selection operator. It combines prediction with variable selection by shrinking some coefficients toward zero and potentially setting some exactly to zero.
Lasso is useful when:
There are many predictors.
Predictors are correlated.
A simpler model is desirable.
Overfitting is a concern.
Different regression procedures may produce slightly different predictive results. Their performance should be compared using appropriate validation methods rather than relying only on how well the model fits the original data.
Further Development in R and Data Science
Python
Python is another major language for data science. It is also a general-purpose programming language, so it can be used for tasks beyond statistics and data analysis.
R and Python overlap substantially in their data-science capabilities. Comparing the two can help users understand:
Different programming styles.
Different package ecosystems.
Strengths of statistical computing versus general-purpose programming.
Alternative ways to manipulate, visualize, and model data.
Data Visualization
Learning the syntax of R’s visualization packages is not the same as learning effective visual design.
Good visualization requires understanding:
The analytical purpose of a graph.
Appropriate visual encodings.
Clear labeling.
Perceptual accuracy.
Avoidance of unnecessary decoration.
Effective comparison.
Appropriate information density.
R provides powerful visualization tools, but the quality of a graph depends on design decisions as well as programming skill.
Machine Learning
Machine learning involves methods that process data to identify patterns and generate predictions.
A central goal is generalization: learning patterns from one data set that can be applied usefully to new observations.
Machine learning includes methods for:
Prediction
Classification
Clustering
Dimensionality reduction
Model evaluation
Large-scale data processing
R and Python both provide extensive machine-learning tools.
R Community
The R community includes:
Large online repositories.
User conferences.
Local user groups.
Package developers.
Researchers and practitioners who share code and documentation.
Community participation helps users find solutions, discover new methods, and stay informed about developments in the language.
Core Workflow for R Data Analysis
A practical R workflow can be summarized as follows:
Install R and, optionally, RStudio.
Organize scripts and data files in a logical project structure.
Load required packages only when needed.
Import or enter data.
Inspect the data with functions such as
head()andsummary().Check data types and structures.
Visualize variables and relationships using bar charts, histograms, scatterplots, and other graphs.
Select or create subsamples when focused analysis is needed.
Calculate descriptive statistics for numerical precision.
Choose an appropriate model, such as clustering, PCA, or regression.
Inspect model output and assumptions, including residuals and possible outliers.
Customize and communicate results with clear graphics and reproducible documents.
Unload or detach packages and clear objects when appropriate.
The most important general principle is to examine data visually before relying on numerical modeling, because plots often reveal distributional structure, outliers, group differences, and violations of assumptions that summary statistics alone cannot show.

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